I have some issue with ASP.net Gridview that I hope people here can help me.
Requirements
Gridview whole row to be clickable to open another page
In editing mode, can change table values through edititemtemplate textbox
Problem
Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.
ASP Page
<asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
OnRowEditing="remarksGV1_RowEditing"
OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
OnRowUpdating="remarksGV1_RowUpdating"
AutoPostBack="false"
HeaderStyle-CssClass="thead-dark"
CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="titleTB" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
<asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
<asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void BindGrid()
{
Debug.WriteLine("BindGrid called");
int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository remarksRepository = new ProjectRepository();
var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
remarksGV1.DataSource = remarks;
remarksGV1.DataBind();
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
}
protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
}
catch
{
//...throw
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);
int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository repository = new ProjectRepository();
var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
Debug.WriteLine("Remarks Count: " + remarks.Count);
TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));
if (titleTB != null)
{
titleTB.Text = remark.REM_TITLE;
}
}
}
protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
{
int row = remarksGV1.SelectedIndex;
long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
Debug.WriteLine("REM ID: " + rem_id);
Session["edit_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["rem_id"] = rem_id.ToString();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
}
protected void btnAddRemarks_Click(object sender, EventArgs e)
{
Session["new_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
string url = "Project_Remarks_In_1.aspx";
Launch.ToPage(this, url, pairs);
}
private void SetTitle()
{
ProjectRepository repository = new ProjectRepository();
TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
this.Title = "Remarks - " + project.PROJ_TITLE;
}
protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
{
remarksGV1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Do stuff
ProjectRepository repository = new ProjectRepository();
GridViewRow row = remarksGV1.Rows[e.RowIndex];
TextBox titleTB = (row.FindControl("titleTB") as TextBox);
long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
var db = new THPEntities();
TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
.First(x => x.REM_ID == rem_id);
remark.REM_TITLE = titleTB.Text;
remark.UPD_DATE = DateTime.Now;
db.SaveChanges();
// Bind Grid
remarksGV1.EditIndex = -1;
BindGrid();
}
protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
remarksGV1.EditIndex = -1;
BindGrid();
}
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
In asp.net Gridview has an empty cell, so when i export it to excel i get   in that empty cell.
I want to replace that with a blank space.
How do i do it?
Here is my GridView :
<asp:GridView Width="800px" ID="MyGridView" DataSourceID="DataSource1" AutoGenerateColumns="False"
runat="Server" BorderColor="#555555" HorizontalAlign="Center" OnRowDataBound="MyGridView_RowDataBound"
Font-Names="Verdana" Font-Size="12px" AllowSorting="True"
EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
<EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>
<Columns>
<asp:BoundField HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
</Columns>
</asp:GridView>
Here is my excel export :
public void ExpToExcel_Click(object sender, EventArgs e)
{
MyGridView.DataBind();
MyGridView.AllowPaging = false;
MyGridView.ShowHeader = true;
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in MyGridView.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
int cellcount = MyGridView.Rows[0].Cells.Count;
foreach (GridViewRow row in MyGridView.Rows)
{
DataRow datarw;
datarw = dt.NewRow();
for (int i = 0; i < cellcount; i++)
{
datarw[i] = row.Cells[i].Text;
}
dt.Rows.Add(datarw);
}
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
workSheet.Cells["J1"].Style.Font.Size = 24;
workSheet.Cells["J1"].Style.Font.Bold = true;
workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
workSheet.Cells["I2"].Style.Font.Size = 20;
workSheet.Cells["I2"].Style.Font.Bold = true;
workSheet.Cells["J3"].Value = caption.Text.ToUpper();
workSheet.Cells["J3"].Style.Font.Bold = true;
workSheet.Cells["L4"].Value = "(UnCertified Data)";
workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells[7, 1].LoadFromDataTable(dt, true);
workSheet.Cells["A7:F7"].AutoFitColumns();
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Enrollment_Major_Classification.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
So in the college name column i get   which i want to remove.
I tried using TRIM but did not work.
Any other suggestions?
I see that you're recreating the styling from the GridView into your Excel file, this requires that when you change the GridView styling you must change the code for Excel file as well.
You could avoid this by creating an Excel file from the GridView's HTML representation, for example see the following:
protected void ExpToExcel_Click(object sender, EventArgs e)
{
// Get MyGridView control's HTML representation.
var plainWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(plainWriter);
this.MyGridView.RenderControl(htmlWriter);
// Load HTML into ExcelFile.
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
var htmlOptions = new HtmlLoadOptions();
var htmlStream = new MemoryStream(htmlOptions.Encoding.GetBytes(plainWriter.ToString()));
var excel = ExcelFile.Load(htmlStream, htmlOptions);
// Download ExcelFile to current HttpResponse.
excel.Save(this.Response, "Enrollment_Major_Classification.xlsx");
}
public override void VerifyRenderingInServerForm(Control control)
{
/* We're overriding this verification because of the "MyGridView.RenderControl" call.
* This confirms that the "HtmlForm" control is rendered for "MyGridView" at run time. */
}
Note, the code uses GemBox.Spreadsheet library.
The following is the result:
This way any change on GridView will be reflected in Excel file as well, without changing the code. As an FYI, I've taken the code from this article.
You should bind your data to a DataTable (as suggested by Scott Hannen)
Here is a fully working example based on your former code
I've also updated the gridview aspx definition (footertext) and also, rowdatabound event
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyGridView.DataSource = LoadData();
MyGridView.DataBind();
}
private DataTable LoadData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[6] { new DataColumn("COLLEGE", typeof(string)),
new DataColumn("COLLEGE DESC", typeof(string)),
new DataColumn("UNDERGRADUATE",typeof(double)),
new DataColumn("GRADUATE",typeof(double)),
new DataColumn("LAW",typeof(double)),
new DataColumn("TOTAL",typeof(double)),
});
dt.Rows.Add("AG", "College of Ag Sci and", 1902, 401, 0, 2303);
dt.Rows.Add("AR", "College of Architecture", 510, 89, 0, 599);
dt.Rows.Add("AS", "Coll of Arts and Science", 9558, 1281, 0, 10839);
dt.Rows.Add("BA", "Rawls Coll of Business", 4042, 574, 0, 4616);
dt.Rows.Add("ED", "College of Education", 823, 1373, 0, 2196);
dt.Rows.Add("EN", "College of Engineering", 4912, 826, 0, 5738);
dt.Rows.Add("GR", "Graduate School", 0, 254, 0, 254);
dt.Rows.Add("HR", "Honors College", 22, 0, 0, 22);
dt.Rows.Add("HS", "College of Human ...", 2813, 464, 0, 3277);
dt.Rows.Add("LW", "School of Law", 0, 0, 445, 445);
dt.Rows.Add("MC", "Coll of Media and ...", 1855, 232, 0, 2087);
dt.Rows.Add("UN", "Texas Tech University", 3497, 4, 0, 3501);
dt.Rows.Add("VP", "Coll of Visual and", 803, 316, 0, 1119);
return dt;
}
protected void Export_Click(object sender, EventArgs e)
{
using (ExcelPackage excel = new ExcelPackage())
{
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
workSheet.Cells["J1"].Style.Font.Size = 24;
workSheet.Cells["J1"].Style.Font.Bold = true;
workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
workSheet.Cells["I2"].Style.Font.Size = 20;
workSheet.Cells["I2"].Style.Font.Bold = true;
workSheet.Cells["J3"].Value = "test".ToUpper();
workSheet.Cells["J3"].Style.Font.Bold = true;
workSheet.Cells["L4"].Value = "(UnCertified Data)";
workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);
var dt = MyGridView.DataSource as DataTable;
// add total row to datatable for excel export because rowdatabound event which already calculates total doesn't make total as a part of the datatable at this time
double totalUnderG = 0;
double totalGrad = 0;
double totalLaw = 0;
double total = 0;
foreach (var r in dt.Rows.Cast<DataRow>())
{
totalUnderG += double.Parse(r[2].ToString());
totalGrad += double.Parse(r[3].ToString());
totalLaw += double.Parse(r[4].ToString());
total += double.Parse(r[5].ToString());
}
dt.Rows.Add("TTU TOTAL", "", totalUnderG, totalGrad, totalLaw, total);
workSheet.Cells[7, 1].LoadFromDataTable(dt, true);
workSheet.Cells["A7:F7"].AutoFitColumns();
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Enrollment_Major_Classification.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
// Declare variable used to store value of Total
double totalUnderG = 0;
double totalGrad = 0;
double totalLaw = 0;
double total = 0;
/// <summary>
/// calculates total when displaying gridview
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check row type
if (e.Row.RowType == DataControlRowType.DataRow)
{
totalUnderG += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "UNDERGRADUATE"));
totalGrad += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "GRADUATE"));
totalLaw += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "LAW"));
total += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "TOTAL"));
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[2].Text = String.Format("{0:N}", totalUnderG);
e.Row.Cells[3].Text = String.Format("{0:N}", totalGrad);
e.Row.Cells[4].Text = String.Format("{0:N}", totalLaw);
e.Row.Cells[5].Text = String.Format("{0:N}", total);
}
}
}
and aspx :
<asp:GridView Width="800px" ID="MyGridView" AutoGenerateColumns="False" OnRowDataBound="MyGridView_RowDataBound"
runat="Server" BorderColor="#555555" HorizontalAlign="Center"
Font-Names="Verdana" Font-Size="12px" AllowSorting="True" ShowFooter="true"
EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
<EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>
<Columns>
<asp:BoundField FooterText="TTU TOTAL" HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
ReadOnly="true" DataFormatString="{0:N0}" />
<asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
ReadOnly="true" DataFormatString="{0:N0}" />
<asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="Button1" runat="server" OnClick="Export_Click" Text="Export" />
</p>
I want to call a Code Behind method inside a Gridview.
This is the Code Behind method that loops through every webcontrol that’s in the form:
private void SetupJSdataChange(Control parentControl)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
And I want it to loop through every webcontrol that’s in a RowCreated gridview's handler instead. This is my try:
protected void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
}
But I get an error that says "the name 'parentControl' doesn't exist in the current context" and I don't know how to handle it.
And this is the Gridview:
<asp:GridView ID="GVTrabajadores" runat="server"
CssClass="table table-hover table-striped"
ShowHeaderWhenEmpty = "true"
GridLines="None"
AutoGenerateColumns="False"
ShowFooter="true"
OnRowCreated="GVTrabajadores_RowCreated"
OnRowCommand="GVTrabajadores_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Nombre">
<ItemTemplate>
<asp:TextBox ID="TxNombre" runat="server" Text='<%#Eval("nombre") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxNombref" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cerrada">
<ItemTemplate>
<asp:CheckBox ID="CBCerrada" runat="server" Checked='<%# (Eval("cerrada").ToString() == "1" ? true : false) %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="CBCerradaf" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This should work for you. Note that I used generic event args - if you need them you'll need to change them.
private void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView gV = sender as GridView;
for(int i = 0; i < gV.Columns.Count; i++)
{
Control c = e.Row.Cells[i].Controls[0];
string controlType = c.GetType().ToString().Replace("System.Web.UI.WebControls.", "");
switch (controlType)
{
case "TextBox":
TextBox t = c as TextBox;
t.TextChanged += GVTrabajadores_TextBox_TextChanged;
t.AutoPostBack = true;
break;
case "CheckBox":
CheckBox cB = c as CheckBox;
cB.CheckedChanged += GVTrabajadores_CheckBox_Changed;
cB.AutoPostBack = true;
break;
}
}
}
private void GVTrabajadores_CheckBox_Changed(object sender, EventArgs e)
{
//process change
}
private void GVTrabajadores_TextBox_TextChanged(object sender, EventArgs e)
{
//process changed text
}
I have a datatable containing all my data called dtData. That datatable contains task descriptions with a task due date for every task description.
Here is what I want to do:
The user selects the month and year from a dropdown and clicks on a button.
Depending upon the number of days in the selected month, a number of panels are generated. (If there are 30 days, 30 panels are generated).
Each panel would correspond to a day in the month and would display the date accordingly.
If the date displayed on the panel matches the task due date for my data, then the corresponding task description is to be displayed in the panel.
I have been able to render the calendar view as I want it but for some reason, while trying the following code to display the necessary task descriptions, a NullReferenceException is thrown.
I debugged the code and the exception is thrown on the following line for the second time the loop which contains it is run (It runs perfectly fine the for the first time):
DateTime p_time = Convert.ToDateTime(((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[1]);
Here is my complete code:
My aspx:
<asp:Repeater ID="rptr_timeline" runat="server" OnItemDataBound="GetChildData">
<ItemTemplate>
<asp:Panel ID="pnl_timeline" runat="server" BackColor="LightGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px">
<span id="span_day">Day</span> <asp:Label ID="lbl_day_number" runat="server" Text='<%# Eval("Day_Number").ToString() %>'></asp:Label>
<span id="span_date">Date:</span> <asp:Label ID="lbl_day_date" runat="server" Text='<%# Eval("Day_Date").ToString() %>'></asp:Label>
<asp:Label ID="lbl_day_name" runat="server" Text='<%# Eval("Day_Name").ToString() %>'></asp:Label><br />
<asp:Repeater ID="rptr_tasks" runat="server">
<ItemTemplate>
<asp:Label ID="lbl_task_name" runat="server" Text='<%# Eval("taskdescription_responsible").ToString() %>'></asp:Label>
</ItemTemplate>
<SeparatorTemplate>
<br /><br />
</SeparatorTemplate>
</asp:Repeater>
</asp:Panel>
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
And here is my code behind:
protected void Load_Dateline(object sender, EventArgs e)
{
try
{
int counter = 0;
int months_days_number = 0;
int month_selected = 0;
int year_selected = 0;
month_selected = Convert.ToInt32(drpdwn_month.SelectedItem.Value);
year_selected = Convert.ToInt32(drpdwn_year.SelectedItem.Value);
months_days_number = DateTime.DaysInMonth(year_selected, month_selected);
DataTable dtMonthdays = new DataTable();
dtMonthdays.Columns.Add("Day_Number");
dtMonthdays.Columns.Add("Day_Date");
dtMonthdays.Columns.Add("Day_Name");
dtMonthdays.Columns.Add("ProperDate");
for (counter = 1; counter <= months_days_number; counter++)
{
DataRow new_row = dtMonthdays.NewRow();
if (counter < 10)
{
new_row["Day_Number"] = "0" + counter.ToString();
}
else
{
new_row["Day_Number"] = counter.ToString();
}
new_row["Day_Date"] = counter.ToString() + "/" + drpdwn_month.SelectedItem.Value.ToString() + "/" + year_selected.ToString();
DateTime temp_date = new DateTime(year_selected, month_selected, counter);
new_row["Day_Name"] = temp_date.ToString("dddd");
dtMonthdays.Rows.Add(new_row);
}
rptr_timeline.DataSource = dtMonthdays;
rptr_timeline.DataBind();
}
catch (Exception ex)
{
lbl_error.Text = "Something went wrong!<br /><br />" + ex.ToString();
}
}
And the following is called on OnItemDataBound of parent repeater:
protected void GetChildData(Object sender, RepeaterItemEventArgs e)
{
Repeater nestedRepeater = e.Item.FindControl("rptr_tasks") as Repeater;
DataTable dt_new = dtData.Clone();
DateTime p_time = Convert.ToDateTime(((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[1]);
foreach (DataRow dr in dtData.Rows)
{
if (DateTime.Parse(dr["taskduedate_responsible"].ToString()).Equals(p_time.ToString()))
{
dt_new.ImportRow(dr);
}
}
if (dt_new != null && dt_new.Rows.Count != 0)
{
nestedRepeater.DataSource = dt_new;
nestedRepeater.DataBind();
}
}
add check whether currently binding item is an Item. or AlternateItem in your GetChildData method
protected void GetChildData(Object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Do binding
}
}
I have been spending quite long time on research how to do this but had no luck.
<asp:GridView runat="server" ID="TBDSPCGrid"
AutoGenerateColumns="false"
AllowPaging="true"
AllowSorting="false"
DataKeyNames="SPID,CategoryId,Category,RowNum, PurchaseDate, Title, Description,SFItemId"
OnRowDataBound="TBDSPC_RowDataBound"
OnRowCreated="TBDSPC_RowCreated"
OnRowCommand="TBDSPC_Command"
OnPageIndexChanging="TBDSPC_PageIndexChanging"
OnRowDeleting="TBDSPC_OnRowDeleting">
<Columns>
<asp:TemplateField HeaderText="Timeouts" ItemStyle-Width="40px" ItemStyle-Wrap="false"
ItemStyle-CssClass="padding-right">
<ItemTemplate>
<div class="targeted-icons">
<asp:LinkButton runat="server" id="LinkButton1" CommandName="delete" CommandArgument='<%#Eval("SFItemId")%>'
><img src="delete.png" /></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
So what should I do here?
protected void TBDSPCGrid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
// do something
}
I tried this but it is not working...it gave me an error of "object reference not set to an instance of an object"
protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = TargetedSpView.ToTable();
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
this.TBDSPCGrid.DataSource = this.TargetedSpView;
this.TBDSPCGrid.DataBind();
}
break;
}
}
protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = RetrieveData(0, 0); // this is a function I used to get a datatable
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
TBDSPCGrid.DataSource = TargetedSpView;
TBDSPCGrid.DataBind();
}
break;
}
}