Some one please tell me why am getting this error when I click button1
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
The issue is with the dropdown lists. How can I create an instance of them in the button1_ click event?
protected void Button1_Click(object sender, EventArgs e)
{
string day = String.Empty;
string time = String.Empty;
string moduleId = string.Empty;
string moduleName = string.Empty;
DataTable dt = new DataTable();
dt.Columns.Add("ModuleID");
dt.Columns.Add("ModuleName");
dt.Columns.Add("Day");
dt.Columns.Add("Time");
foreach (GridViewRow row in GridView1.Rows)
{
DropDownList ddl_day = new DropDownList(); // wont work, I tried it!
day = ((DropDownList)row.FindControl("ddl_day")).SelectedItem.Value;
time = ((DropDownList)row.FindControl("ddl_time")).SelectedItem.Value;
DataRow dr = dt.NewRow();
// dr[0] = row.Cells[i].Text;
/* dr["ModuleID"] = moduleId;
dr["ModuleName"] = moduleName;*/
dr["Day"] = day;
dr["Time"] = time;
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.DataSetName = "Student_module_data";
ds.Tables.Add(dt);
ds.WriteXml(@"E:\OBJECT ORIENTED DEV'T\xml_data\testing.xml");
}
Here is my html
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText="Day">
<ItemTemplate>
<asp:DropDownList ID="ddl_days" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:DropDownList ID="ddl_time" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
It look like following line return with null
((DropDownList)row.FindControl("ddl_day"));
And as you are try to use its property it is giving null reference error. So check if it is null or not.
var ddl_day = ((DropDownList)row.FindControl("ddl_day"));
if(ddl_day!=null)
{
day = ddl_day.SelectedItem.Value;
}
Check Same for other dropdown also.
Change the DropdownList ID from ddl_days
to ddl_day
in your HTML code, as Zaki told in the comment. This is the primary issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.