I want to display Agendas from table "tblAgenda" using Asp.net here is the query:
public static List<int> SelectByYear()
{
DbManager db = new DbManager();
try
{
List<int> list = new List<int>();
var result = from p in db.tblAgenda
group p by p.News.Value.Year
into g
select new { Year = g.Key, Releases = g };
foreach (var obj in result)
{
list.Add(obj.Year);
}
list.Reverse();
return list.ToList<int>();
}
catch
{
return null;
}
finally
{
db.Dispose();
}
}
and here I am calling the above method:
public partial class edd_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["id"]))
{
RecentData();
}
}
}
private void RecentData()
{
List<tblAgenda> agd = new List<tblAgenda>();
StringBuilder sbHeadings = new StringBuilder();
StringBuilder sbData = new StringBuilder();
List<int> list1 = AgendaManager.SelectByYear();
if (list1 != null)
{
List<int> list = list1.Take(3).ToList<int>();
int Row = 0;
string RowCss = "";
foreach (tblAgenda ob in agd)
{
strYears = "";
if (list.Count > 0)
{
Table tblHead = new Table();
TableRow trHead = new TableRow();
TableCell tcDvHead = new TableCell();
TableCell tcLnkHead = new TableCell();
for (int i = 0; i < list.Count; i++)
{
Row = 0;
List<clsAgenda> listData = new List<clsAgenda>();
listData = null;
DateTime dt = DateTime.Now.AddYears(1);
string stryr = strYears;
int intyr = Convert.ToInt32(list[i]);
diff = Convert.ToInt32(dt.Year) - Convert.ToInt32(intyr);
if (diff == 0 || diff == 1 || diff == 2)
{
if (drpDepartments.SelectedValue == "-1")
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]));
}
else
{
if (AgendaManager.IsAgendExistForDeptartment(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue)))
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
}
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue));
}
sbData.Append("<table id='tbl" + list[i] + "' cellspacing='1' cellpadding='4' width='885' style='display:none;margin-top:10px;' class='GridBorder' >");
sbData.Append("<tr class='GridViewHeaderStyle' >");
sbData.Append("<th style='width:380px;height:22px;text-align:left;'>Meeting</th><th style='height:22px;text-align:left;'>Date</th><th style='width:70px;height:22px;text-align:left;'>Time</th><th style='width:70px;height:22px;text-align:left;'>Agenda</th><th style='height:22px;text-align:left;width:120px;'>Web Cast</th><th style='height:22px;text-align:left;width:100px;'>Minutes</th>");
sbData.Append("</tr>");
foreach (clsAgenda obj in listData)
{
RowCss = "";
if (Row == 1)
{
RowCss = "class='GridRow'";
}
sbData.Append("<tr " + RowCss + ">");
sbData.Append("<td >" + obj.Title + "</td>");
sbData.Append("<td >" + string.Format("{0:MMM dd, yyyy}", obj.AgendaDate) + "</td>");
sbData.Append("<td >" + obj.Time + "</td>");
sbData.Append("<td ><a style='color:black;' href='agenda.aspx?id=" + obj.ID + "'>View</a></td>");
if (string.IsNullOrEmpty(obj.WebCast))
{
sbData.Append("<td >---</td>");
}
else
{
sbData.Append("<td ><a style='color:black;' href='" + obj.WebCast + "'>" + obj.WebCastTitle + "</a></td>");
}
if (string.IsNullOrEmpty(obj.MinutesFile))
{
sbData.Append("<td >---</td>");
}
else
{
if (ob.showThroughBroswer == 1)
{
sbData.Append("<td ><a href='downloadfile.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
else
{
sbData.Append("<td ><a href='showpdf.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
}
sbData.Append("</tr>");
Row++;
if (Row == 2)
{
Row = 0;
}
}
sbData.Append("</table>");
}
else
break;
}
if (strYears.Length > 0)
{
strYears = strYears.Substring(0, strYears.Length - 1);
}
strFirstYear = list[0].ToString();
tcDvHead.Text = sbHeadings.ToString();
if (diff == 1 || diff == 2)
{
tcLnkHead.Text = "<div class='dvhrfclass'><a href='listagendas.aspx?id=pre' class='link1'>Previous Meetings >></a></div>";
}
else
{
tcLnkHead.Text = "";
}
trHead.Cells.Add(tcDvHead);
trHead.Cells.Add(tcLnkHead);
tblHead.Rows.Add(trHead);
StringWriter sW = new StringWriter();
HtmlTextWriter hW = new HtmlTextWriter(sW);
tblHead.RenderControl(hW);
letHeading.Text = sW.ToString();
letData.Text = sbData.ToString();
}
}
}
}
now the issue is I am getting no values in list1, I have tried using the debugger on the query and found that I can't access the "tblAgenda", its giving an error that: " Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation". I have searched alot but didn't find anything good, my connection string is totally fine because all the other tables are working fine even in "tblAgenda" I can store new agenda from admin panel but I can't retrieve the agendas on front end, what is the issue here?
Thanks.
I have two repeater controls one inside other and in inner repeater there is placeholder in which radio button is dynamically generated. I want to find the radio button control to check whether it is checked or not? I want above all function to be performed in button submit/click event defined in the code?
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
strqry = "select * from Quiz_tblQsnsLimitMaster where Qsnexamname='" + Request.QueryString["QsnEname"].ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(strqry, sCon);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
int total = ds.Tables[0].Rows.Count;
for (int i = 0; i < total; i++)
{
string QuesID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
//SubName = ds.Tables[0].Rows[i].ItemArray[3].ToString();
DataSet oDs = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_OnlineTest_QuestionsWithOptions_Get", QuesID);
SomeDatatable.Merge(oDs.Tables[0]);
}
removeDuplicatesRows(SomeDatatable);
System.Data.DataColumn newColumn = new System.Data.DataColumn("ContentIndex", typeof(System.String));
newColumn.DefaultValue = "0";
SomeDatatable.Columns.Add(newColumn);
for (int i = 0; i < Math.Ceiling((decimal)SomeDatatable.Rows.Count); i++)
SomeDatatable.Rows[i]["ContentIndex"] = i + 1;
}
catch
{
}
////2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
//BindSubject();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
//TablLinkRepeater.DataSource = TabList;
//TablLinkRepeater.DataBind();
//}
}
public void removeDuplicatesRows(DataTable dt)
{
SomeDatatable = dt.DefaultView.ToTable(true, "QuestionId");
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
// This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
var parsed = "'" + HttpUtility.ParseQueryString(DataBinder.Eval(e.Item.DataItem, "QuestionID").ToString()) + "'";
//Add Question
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", Convert.ToString(parsed));
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = new Unit("98%");
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Font.Size = 12;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = ContentIndex.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
oRbOptions.Font.Size = 11;
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
//oRbOptions.Enabled = false;
//if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
//{
// oRbOptions.Checked = true;
//}
oRbOptions.InputAttributes.Add("data-info", Convert.ToString(ContentIndex));
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview = (PlaceHolder)e.Item.FindControl("PlPreview");
PlPreview.Controls.Add(tblQsn);
}
}
}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
SubmitQuestion();
}
public void SubmitQuestion()
{
for (int c = 0; c < SomeDatatable.Rows.Count; c++)
{
string sQsnOptId = SomeDatatable.Rows[c]["QuestionID"].ToString();
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", "'" + sQsnOptId + "'");
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i-1][2].ToString() + "_" + "Option" + i + "_" + i;
Repeater rpt = (Repeater)TabRepeater.NamingContainer.FindControl("ContentRepeater");
RadioButton rbt = (RadioButton)rpt.NamingContainer.FindControl(rdboption);
if (rbt.Checked)
{
strqry = "update Quiz_tblOnlineTest_Detail set UserAns='Option" + i + "', DeletionStatus='A' where CreationLogInId='AMITSAMBYAL#HOTMAIL.COM' and ExamName='" + Request.QueryString["QsnEname"].ToString() + "' and QsnId=" + Session["quesid"].ToString() + "";
cmd = new SqlCommand(strqry, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
break;
}
}
}
}
}
I found the answer. Thanks
foreach (RepeaterItem repeater in TabRepeater.Items)
{
Repeater repeater1 = (Repeater)repeater.FindControl("ContentRepeater");
foreach (RepeaterItem repItem in repeater1.Items)
{
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i - 1][2].ToString() + "_" + "Option" + i + "_" + i;
PlaceHolder PlPreview = (PlaceHolder)repItem.FindControl("PlPreview");
rbt = (RadioButton)PlPreview.FindControl(rdboption);
if (rbt.Checked)
{
// statement
}
}
}
}
}
}
I have a gridview that works just fine with each of my row commands, however, once it is sorted it causes the rowdatabound event to use incorrect values rather than the actual values in the row after it has been sorted. Any help would be appreciated!
Here is my code behind.
//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
buttonCommand = e.CommandName;
MessageLBL.Text = "";
if (e.CommandName == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID != "38")
{
verifyRenewal = false;
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
//Get row index.
UnverifiedSalesGV.SetEditRow(Convert.ToInt32(e.CommandArgument));
verifyRenewal = true;
}
}
if (e.CommandName == "UpdateProduct")
{
DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
if (productValue.SelectedIndex != 0)
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = #ProductID, Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Please select renewal type.";
}
}
if (e.CommandName == "UpdateRecord")
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [GrossSalesAmount] = #GrossSalesAmount, [NetSalesAmount] = #NetSalesAmount, [Notes] = #Notes, [CommissionMonth] = #CommissionMonth, [DateLastModified] = #DateLastModified, [UserLastModified] = #UserLastModified WHERE [ID] = #ID";
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UnverifiedSalesSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
}
//Get product
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
if (buttonCommand == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
}
}
}
}
I was finally able to solve my problem by hardcoding in the following:
//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == rowIndex)
{
string state = e.Row.RowState.ToString();
if (state == "Alternate, Edit" || state == "Edit")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
Label notesLBL = (Label)e.Row.FindControl("NotesLBL");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
accountManagerLBL.Visible = true;
accountManagerDDL.Visible = false;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
notesLBL.Visible = true;
}
}
}
}
In my ASP.NET project, I add a new array item with the help of query string. once the array item added, my client reload the browser,. so the same item add another time. It happens each reload timing.
but i don't want this. any possible to stop this browser reload or stop the same array item?
my url is -
51402/ItemGrid.aspx?id=3035
then id=3035 item added to the array.
My Code in page load event
string query ="";
int array_no;
if (Convert.ToUInt32(GlobalClass.GlobalarrayNo.ToString()) == 0)
{
array_no = 0;
Array.Clear(roomno, 0, roomno.Length);
}
else
{
array_no = Convert.ToInt32(GlobalClass.GlobalarrayNo.ToString());
}
id = Convert.ToInt32(Request.QueryString["id"]);
if (!Page.IsPostBack)
{
// ******* Happy Status ************
decimal happyfromtime = 0;
string happyper="";
string happytotime = "";
query = "SELECT Parameters_Parameter3,Parameters_Parameter2,Parameters_Parameter1,Parameters_Parameter4 FROM MCS_Parameters WHERE Parameters_TYPE ='HAPHOU'";
MySqlConnection connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
happyfromtime= Convert.ToDecimal(Reader[0].ToString());
happyper=Reader[1].ToString();
happystatus= Convert.ToInt32(Reader[2].ToString());
happytotime = Reader[3].ToString();
}
connection.Close();
string t = GlobalClass.GlobalserverTime.ToString();
t= t.Substring(0,5);
t = t.Replace(":",".");
//ALLTRIM(CurCate.Fb_Item_Creation_HappyhoursStatus)='Yes'
if ((Convert.ToDecimal(t) > Convert.ToDecimal(happyfromtime)) && (Convert.ToDecimal(t) < Convert.ToDecimal(happytotime)) && (happystatus == 1))
{
tHappy_Status = 1;
}
if (GlobalClass.GlobalservedAt == "RST")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RestaurantPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else if (GlobalClass.GlobalservedAt == "BAR")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_BarPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RoomPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
command = new MySqlCommand(query, connection);
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
roomno[array_no, 0] = Reader[0].ToString(); // Fb_Item_Creation_ItemDescription
if (GlobalClass.GlobalopenCode == "OPEN")
{
roomno[array_no, 0] = GlobalClass.GlobalopenDes.ToString(); // Fb_Item_Creation_ItemDescription
roomno[array_no, 1] = GlobalClass.GlobalopenRate.ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = GlobalClass.GlobalopenQty.ToString(); // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
array_no++;
GlobalClass.GlobalarrayNo = array_no;
}
else if (roomno[array_no, 0] == "OPEN")
{
Response.Redirect("OpenItem.aspx" + "?id=" + id);
}
else
{
roomno[array_no, 1] = Reader[1].ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = "1"; // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
if ((tHappy_Status == 1) && (roomno[array_no, 16].ToString()=="Yes"))
{
roomno[array_no, 8] = "Yes";
}
array_no++;
GlobalClass.GlobalarrayNo = array_no;
//var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
//nameValues.Set("sortBy", "4");
//string url = Request.Url.AbsolutePath;
//string updatedQueryString = "?" + nameValues.ToString();
//Response.Redirect(url + updatedQueryString);
}
}
connection.Close();
ViewState["btn"] = "1";
ViewState["tot"] = "0";
ViewState["happystatus"] = happystatus;
btn_click = Convert.ToInt32(ViewState["btn"].ToString());
int len = array_no;
while (len > 8)
{
len = len - 8;
tot++;
}
if (len != 0) tot++;
ViewState["tot"] = tot;
fun();
//CreatingTmpModdbf1();
// Modifier Text
int seq = Convert.ToInt32(Request.QueryString["seq"]);
string text = Request.QueryString["text"];
if (text != null)
{
roomno[seq - 1, 15] = text;
}
}
!postback is not help to avoid my problem.
static class GlobalClass
{
private static string myConnString1 = "";
private static int userId = 0;
private static string userName = "";
private static int outletId = 0;
private static int itemGroupId = 0;
private static DateTime serverDate;
private static string serverTime = "";
private static string tableName = "";
private static string serverdAt = "";
private static int arrayNo = 0;
private static int waiterId = 0;
private static int covers = 0;
private static string kotno = "";
public static string GlobalConnString
{
get { return myConnString1; }
set { myConnString1 = value; }
}
public static int GlobaluserId
{
get { return userId;}
set { userId = value; }
}
public static string GlobaluserName
{
get { return userName; }
set { userName = value; }
}
public static int GlobaloutletId
{
get { return outletId; }
set { outletId = value; }
}
public static DateTime GlobalserverDate
{
get { return serverDate; }
set { serverDate = value; }
}
public static string GlobalserverTime
{
get { return serverTime; }
set { serverTime = value; }
}
public static string GlobaltableName
{
get { return tableName; }
set { tableName = value; }
}
public static int GlobalitemGroupId
{
get { return itemGroupId; }
set { itemGroupId = value; }
}
public static string GlobalservedAt
{
get { return serverdAt; }
set { serverdAt = value; }
}
public static int GlobalarrayNo
{
get { return arrayNo; }
set { arrayNo = value; }
}
public static int GlobalwaiterId
{
get { return waiterId; }
set { waiterId = value; }
}
public static int Globalcovers
{
get { return covers; }
set { covers = value; }
}
public static string GlobalkotNo
{
get { return kotno ; }
set { kotno = value; }
}
public static string staffId = "";
public static string staffCategoryId = "";
public static string GlobalstaffId
{
get { return staffId; }
set { staffId = value; }
}
public static string GlobalstaffCategoryId
{
get { return staffCategoryId; }
set { staffCategoryId = value; }
}
public static string openCode = "";
public static string openDes = "";
public static string GlobalopenCode
{
get { return openCode; }
set { openCode = value; }
}
public static string GlobalopenDes
{
get { return openDes; }
set { openDes = value; }
}
public static string openQty = "";
public static string openRate = "";
public static string GlobalopenQty
{
get { return openQty; }
set { openQty = value; }
}
public static string GlobalopenRate
{
get { return openRate; }
set { openRate = value; }
}
}
I assume that your array is static/shared. Static variables are shared across the whole app domain and all threads. Hence every user uses the same variable.
Don't use static variables therefor, instead of persisting the array you should use the querystring again.
If this was a wrong assumption you should show us your code
After adding item you can redirect to another page. For example 51402/ItemGrid.aspx
Also using get request to save/edit/delete data is not good idea, better use post.
If you are adding the item to the Array within Page_Load, you may want to wrap the code that adds the item in the following:
If Not Page.IsPostBack Then
//Your array item adding code here
End If
This will prevent the item adding again if the user refreshes the page. Though, I'd like to echo Tim and say that if I assumed incorrectly, you should post your code.
I am getting object reference not set to an instance of an object even though my list is not null
protected void gridview_bind()
{
try
{
CompanyMasterClass co = new CompanyMasterClass();
co.strcompany_code = Request.Cookies["userinfo"]["companycode"].ToString();
ResultClass objress = co.fn_GetNameNumberStyle();
if (objress.bStatus)
{
eslist<CompanyMasterClass> OBJLISTS = objress.objData as eslist<CompanyMasterClass>;
if (OBJLISTS.Count > 0)
{
if (OBJLISTS[0].strdatestyle.ToString() == "DM")
{
mskextCreatedOn.Mask = "99/99/9999";
mskextCreatedOn.CultureName = "en-GB";
//mskextCreatedOn.UserDateFormat="DayMonthYear";
mskextUpdatedOn.Mask = "99/99/9999";
mskextUpdatedOn.CultureName = "en-GB";
}
if (OBJLISTS[0].strdatestyle.ToString() == "MD")
{
mskextCreatedOn.Mask = "99/99/9999";
mskextCreatedOn.CultureName = "en-US";
//mskextCreatedOn.UserDateFormat="DayMonthYear";
mskextUpdatedOn.Mask = "99/99/9999";
mskextUpdatedOn.CultureName = "en-US";
}
}
}
//mm.getlookup(ddlUserType, "user_type", "s");
CustomerMasterClass cs = new CustomerMasterClass();
ResultClass objres = cs.fn_GetCustomerMasterGrid();
if (objres.bStatus)
{
eslist<CustomerMasterClass> OBJLIST = objres.objData as eslist<CustomerMasterClass>;
if (OBJLIST.Count > 0)
{
if ((bool)ViewState["filter"] == true)
{
DataTable dts = (DataTable)ViewState["searchtable"];
pds.DataSource = dts.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlPerPage.SelectedValue);
//pds.PageSize = 5;
DataView dvs = dts.DefaultView;
if (this.ViewState["SortExp"] != null)
{
dvs.Sort = this.ViewState["SortExp"].ToString()
+ " " + this.ViewState["SortOrder"].ToString();
}
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
if (pds.IsLastPage)
{
//lnkbtnNext.Style.Add("color", "#CCCCCC");
lnkbtnNext.Style.Add("background-color", "#CCCCCC");
lnkbtnNext.Style.Add("border-width", "0px");
}
else
{
//lnkbtnNext.Style.Remove("color");
lnkbtnNext.Style.Remove("background-color");
lnkbtnNext.Style.Remove("border-width");
}
if (pds.IsFirstPage)
{
//lnkbtnPrevious.Style.Add("color", "#CCCCCC");
lnkbtnPrevious.Style.Add("background-color", "#CCCCCC");
lnkbtnPrevious.Style.Add("border-width", "0px");
}
else
{
//lnkbtnPrevious.Style.Remove("color");
lnkbtnPrevious.Style.Remove("background-color");
lnkbtnPrevious.Style.Remove("border-width");
}
gvCustomerMaster.DataSource = pds;
gvCustomerMaster.DataBind();
doPaging();
// gvGroupMaster.DataSource = OBJLIST;
//gvGroupMaster.DataBind();
gridmain.Visible = true;
//frmvwGroup.Visible = false;
lblTotalRecords.Text = dts.Rows.Count.ToString();
}
else
{
DataTable dt = (DataTable)OBJLIST;
//dt = OBJLIST.ToString();
ViewState["nosearch"] = dt;
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlPerPage.SelectedValue);
//pds.PageSize = 5;
DataView dv = dt.DefaultView;
if (this.ViewState["SortExp"] != null)
{
dv.Sort = this.ViewState["SortExp"].ToString()
+ " " + this.ViewState["SortOrder"].ToString();
}
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
if (pds.IsLastPage)
{
//lnkbtnNext.Style.Add("color", "#CCCCCC");
lnkbtnNext.Style.Add("background-color", "#CCCCCC");
lnkbtnNext.Style.Add("border-width", "0px");
}
else
{
//lnkbtnNext.Style.Remove("color");
lnkbtnNext.Style.Remove("background-color");
lnkbtnNext.Style.Remove("border-width");
}
if (pds.IsFirstPage)
{
//lnkbtnPrevious.Style.Add("color", "#CCCCCC");
lnkbtnPrevious.Style.Add("background-color", "#CCCCCC");
lnkbtnPrevious.Style.Add("border-width", "0px");
}
else
{
//lnkbtnPrevious.Style.Remove("color");
lnkbtnPrevious.Style.Remove("background-color");
lnkbtnPrevious.Style.Remove("border-width");
}
gvCustomerMaster.DataSource = pds;
gvCustomerMaster.DataBind();
doPaging();
// gvGroupMaster.DataSource = OBJLIST;
//gvGroupMaster.DataBind();
gridmain.Visible = true;
//frmvwGroup.Visible = false;
lblTotalRecords.Text = OBJLIST.Count.ToString();
//this.GetUsersPageWise(1);
}
}
}
}
catch (Exception ex)
{
ErrorLogClass ObjError = new ErrorLogClass("customer_master.aspx", "customer_master()", ex);
}
}
I am getting the error at DataTable dt = (DataTable)OBJLIST; in the else clause.
Any ideas or suggestions please?
thanks,
There was a problem in the data. Some values where null. Solved by assigning a default value to the data variables.
you cannot cast a list to a datatable like this.
either use
static DataTable ConvertListToDataTable(eslist<CompanyMasterClass> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
}
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var array in list)
{
table.Rows.Add(array);
}
return table;
}
or refer the following link
http://www.codeproject.com/Articles/83271/Convert-a-Generic-List-to-a-Datatable