Gridview within dynamic dropdownlist null exception

Nov 11 2019 8:30 AM
I have a GridView with template fields and one of the template field is a dropdownlist which is dynamically added into the gridview control. It's working properly on page load when I click the button control to the get the values from the template fields it will throw a null reference exception. Please correct my error, I am in pathetic situation. I attached the source code.
Regards
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCreated="GridView1_RowCreated">  
  2. <Columns>  
  3. <asp:TemplateField>  
  4. <ItemTemplate>  
  5. <asp:Label ID="id" runat="server" Text='<%# Eval("RGNO") %>'></asp:Label>  
  6. </ItemTemplate>  
  7. </asp:TemplateField>  
  8. </Columns>  
  9. <Columns>  
  10. <asp:TemplateField>  
  11. <ItemTemplate>  
  12. <asp:Label ID="name" runat="server" Text='<%# Eval("NAME") %>'></asp:Label>  
  13. </ItemTemplate>  
  14. </asp:TemplateField>  
  15. </Columns>  
  16. <Columns>  
  17. <asp:TemplateField>  
  18. <ItemTemplate>  
  19. <asp:Label ID="lastname" runat="server" Text='<%# Eval("DOB") %>'></asp:Label>  
  20. </ItemTemplate>  
  21. </asp:TemplateField>  
  22. </Columns>  
  23. <Columns>  
  24. <asp:TemplateField>  
  25. <ItemTemplate>  
  26. <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>  
  27. </ItemTemplate>  
  28. </asp:TemplateField>  
  29. </Columns>  
  30. </asp:GridView>  
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3. if (!IsPostBack) BindGridView();  
  4. }  
  5. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)  
  6. {  
  7. if (e.Row.RowType == DataControlRowType.DataRow)  
  8. {  
  9. DropDownList ddlResult = new DropDownList();  
  10. ddlResult.ID = "ddlResult";  
  11. ddlResult.Items.Insert(0, new ListItem("PASS""0"));  
  12. ddlResult.Items.Insert(1, new ListItem("FAIL""1"));  
  13. PlaceHolder p = (PlaceHolder)e.Row.FindControl("PlaceHolder1");  
  14. p.Controls.Add(ddlResult);  
  15. }  
  16. }  
  17. private void BindGridView()  
  18. {  
  19. GridView1.DataSource = CreateDataSource();  
  20. GridView1.DataBind();  
  21. }  
  22. public DataTable CreateDataSource()  
  23. {  
  24. DataTable dt = new DataTable();  
  25. DataRow dr;  
  26. dt.Columns.Add(new DataColumn("RGNO"typeof(string)));  
  27. dt.Columns.Add(new DataColumn("NAME"typeof(string))); 
  28. dt.Columns.Add(new DataColumn("DOB"typeof(string)));  
  29. dr = dt.NewRow();  
  30. dr["RGNO"] = "1001";  
  31. dr["NAME"] = "PRAKASH";  
  32. dr["DOB"] = "10-10-2003";  
  33. dt.Rows.Add(dr);  
  34. return dt;  
  35. }  
  36. protected void Button1_Click(object sender, EventArgs e)  
  37. {  
  38. foreach (GridViewRow row in GridView1.Rows)  
  39. {  
  40. DropDownList dd1 = (DropDownList)row.FindControl("ddlResult");  
  41. Response.Write(dd1.SelectedItem.Text);  
  42. }  
  43. }

Answers (1)