How to read each row of grid - asp.net

I am trying to use a tool tip on every row of a grid to show details whenever user place pointer on particular cell. It's supposed to show details for every row but it only shows details for the first row. Can any one help me?
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells[i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}
e.Row.Cells[i].ToolTip = tooltip;
}
}

You can use another foreach in order to loop all rows :
foreach (GridViewRow row in GridView.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//do your staff
}
}
But for me, you should use GridView_RowDataBound event :
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells [i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}`enter code here`
e.Row.Cells[i].ToolTip = tooltip;
}
}
}
}

Related

Error: Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation

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.

Grid view event not getting triggered

I have a gridview created dynamically , now i am trying to do edit each column by keeping a link button. But the rowdatabound event is not getting triggered.Where i might have gone wrong?
Below is my code :
dtValues = gObj.GetAllDocumentsHistoryList();
dtHeader = gObj.GetAllHeaderList();
GridView gvEmployee = new GridView();
gvEmployee.ShowHeaderWhenEmpty = true;
gvEmployee.EmptyDataText = "Sorry No History Records Found !!!!!!!";
gvEmployee.AutoGenerateColumns = false;
for (int i = 0; i < dtValues.Columns.Count; i++)
{
string name = dtValues.Columns[i].ColumnName.ToString();
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
for (int j = 0; j < dtHeader.Rows.Count; j++)
{
if (dtHeader.Rows[j]["ColCode"].ToString() == dtValues.Columns[i].ColumnName.ToString())
{
boundfield.HeaderText = dtHeader.Rows[j]["ColName"].ToString();
if (boundfield.HeaderText.Contains("Date") || boundfield.HeaderText.Contains("DocExpiry"))
{
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
else if (dtValues.Columns[i].ColumnName.ToString() == "Last Modified Date")
{
boundfield.HeaderText = "Last Modified Date";
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
gvEmployee.Columns.Add(boundfield);
}
gvEmployee.DataSource = dtValues;
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}
Just add your RowDataBound handler before DataBind.
Corrected Code:
gvEmployee.DataSource = dtValues;
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");

Find radio button control in nested repeater control in asp.net?

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
}
}
}
}
}
}

HOw can I handle Dynamically generated Controls

In the following image the table displayed is generated dynamically on click of “Create Table” button.
I have added textboxes, fileupload, Buttons dynamically to the table.
I want to upload files from fileupload control on click of “Upload” button in the Table, but I have no idea how to handle those Dynamically generated Controls.
Code of “Create Table” button goes like this :
protected void Button1_Click(object sender, EventArgs e)
{
//Button1.Visible = false;
//Creat the Table and Add it to the Page
Table table = new Table();
table.Caption = "Table1";
table.BackColor = System.Drawing.Color.BurlyWood;
Page.Form.Controls.Add(table);
for (int i = 0; i < 3; i++)
{
TableRow row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
for (int j = 0; j <= 10; j++)
{
TableCell cell = new TableCell();
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= 0; j++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + i + "Col" + j;
lbl.Text = "CC NO. " + i + " ";
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 1; j <= 1; j++)
{
Label lbl = new Label();
lbl.ID = "lblRow" + i + "Col" + j;
lbl.Width = 100;
lbl.Text = Convert.ToString(DateTime.Now.Day) + "/" + Convert.ToString(DateTime.Now.Month) + "/" + Convert.ToString(DateTime.Now.Year);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 2; j <= 7; j++)
{
TextBox tb = new TextBox();
tb.Width = 100;
tb.ID = "txtBoxRow" + i + "Col" + j;
tb.Text = "";
// Add the control to the TableCell
cell.Controls.Add(tb);
}
for (j = 8; j <= 8; j++)
{
FileUpload fileUp = new FileUpload();
fileUp.ID = "flupRow" + i + "Col" + j;
fileUp.Width = 220;
cell.Controls.Add(fileUp);
}
for (j = 9; j <= 9; j++)
{
Button btnUpld = new Button();
btnUpld.Width = 100;
btnUpld.ID = "btnUpRow" + i + "Col" + j;
btnUpld.Text = "Upload";
cell.Controls.Add(btnUpld);
}
for (j = 10; j <= 10; j++)
{
Label lbl = new Label();
lbl.ID = "lblRow" + i + "Col" + j;
lbl.Text = "[ Status ]";
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
//table.Rows.Add(row);
}
Attach event handeler btnUpld runtime.
Button btnUpld = new Button();
btnUpld.Width = 100;
btnUpld.ID = "btnUpRow" + i + "Col" + j;
btnUpld.Text = "Upload";
btnUpld.Click += new EventHandler(btnUpld_Click);
cell.Controls.Add(btnUpld);
//code behind
private void btnUpld_Click(object sender, System.EventArgs e)
{
// Add upload functionality here
}
btnUpload.Click +=new EventHandler(btnUpload_Click);
add an event handler after adding the control dynamically to the form, using the above code and then add create a function that handles this event using the following code
protected void btnEdit_Click(object sender, EventArgs e)
{
}

Object reference not set to an instance of an object datatable

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

Resources