hello i want to read the gridview dropdownlist and i apply the code foreach but inbenefit3 = ((tb3.SelectedValue.ToString())); tb3 it returns error null and object reference not set to an instance
how to read the gridview items
here is my code i highlight the code
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity.Infrastructure;
namespace WebApplication14
{
public partial class WebForm63 : System.Web.UI.Page
{
// mann mode = new mann();
//protected void Page_Load(object sender, EventArgs e)
//{
// if (!IsPostBack)
Based on the code you provided, I created a demo and modified the code.
If you break the point and run the program at the corresponding position, the issues you encountered may be like this:
The reason for this issues is that only when you click the Edit button will a DropDownList be generated in the corresponding row. DropDownList does not exist in other rows of GridView.
You could make some modifications to the code to meet your needs, please refer below code:
Code Behind:
public partial class FillDrooDownList : System.Web.UI.Page
{
String conStr = "data source =.; database=TestDB; integrated security = SSPI";
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
bindData();
}
}
private void bindData()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
String query = "select * from tableTest";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
//private void fillDropDownList()
private void fillDropDownList(int rowIndex)
{
DropDownList ddl = (DropDownList)GridView1.Rows[rowIndex].FindControl("dd31");
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
String query = "select id from tableTest";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
//foreach (GridViewRow row in GridView1.Rows)
//{
//DropDownList ddl = (DropDownList)row.FindControl("dd31");
ddl.DataSource = dt;
ddl.DataValueField = "id";
ddl.DataBind();
//}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindData();
//fillDropDownList();
fillDropDownList(e.NewEditIndex);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
}
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
55 Points
191 Posts
in foreach dropdownlist not read items error occur objectreference not set?
Jun 16, 2020 10:08 AM|prabhjot1313|LINK
hello i want to read the gridview dropdownlist and i apply the code foreach but inbenefit3 = ((tb3.SelectedValue.ToString())); tb3 it returns error null and object reference not set to an instance
how to read the gridview items
here is my code i highlight the code
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity.Infrastructure;
namespace WebApplication14
{
public partial class WebForm63 : System.Web.UI.Page
{
// mann mode = new mann();
//protected void Page_Load(object sender, EventArgs e)
//{
// if (!IsPostBack)
// Clear();
// showdata();
//}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
this.BindGrid1();
//fillgridview2();
}
}
private void BindGrid()
{
using (hospitalEntities ctx = new hospitalEntities())
{
Gv2.DataSource = (from hospitalEntities in ctx.manns
select hospitalEntities).ToList();
Gv2.DataBind();
}
}
private void BindGrid1()
{
using (hospitalEntities ctx = new hospitalEntities())
{
dd3.DataSource = (from hospitalEntities in ctx.manns
select hospitalEntities).ToList();
dd3.DataBind();
}
}
public void fillgridview2()
{
using (hospitalEntities ctx = new hospitalEntities())
{
foreach (GridViewRow gr3 in Gv2.Rows)
{
string benefit3 = "0";
DropDownList tb3 = (DropDownList)gr3.FindControl("dd31");
benefit3 = ((tb3.SelectedValue.ToString()));
DropDownList bn18 = ((DropDownList)gr3.FindControl("dd31"));
bn18.Text = benefit3;
bn18.DataSource = (from hospitalEntities in ctx.manns
select hospitalEntities).ToList();
// dd3.DataBind();
for (int i = 0; i < Gv2.Rows.Count; i++)
{
try
{
((DropDownList)Gv2.Rows[i].FindControl("dd31")).DataSource = bn18.DataSource;
((DropDownList)Gv2.Rows[i].FindControl("dd31")).DataBind();
}
catch { }
}
}
}
}
//public void showdata()
//{
// using (hospitalEntities ctx = new hospitalEntities())
// Gv2.DataSource = (from hospitalEntities in ctx.manns select hospitalEntities).ToList();
// Gv2.DataBind();
//}
void Clear()
{
//tb_benefited.Text = tb_allowance.Text = "";
//Button1.Text = "save";
}
protected void Button1_Click(object sender, EventArgs e)
{
//mode.benefited_leaves1 = tb_benefited.Text.Trim();
//mode.basic_allowance1 = tb_allowance.Text.Trim();
using (hospitalEntities ctx = new hospitalEntities())
{
// db1.manns.Add(mode);
// db1.SaveChanges();
ctx.manns.Add(new mann()
{
benefited_leaves1 = dd3.SelectedItem.ToString(),
basic_allowance1 = tb_allowance.Text
});
ctx.SaveChanges();
BindGrid1();
//showdata();
//Clear();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
using (hospitalEntities ctx1 = new hospitalEntities())
{
//var author = ctx1.manns.First(a => a.tbl_id == 1);
//author.basic_allowance1 = tb_allowance.Text;
//ctx1.SaveChanges();
var author = ctx1.manns.First(a => a.tbl_id == 1);
author.basic_allowance1 = tb_allowance.Text;
ctx1.SaveChanges();
}
}
//protected void Gv2_RowDataBound(object sender, GridViewRowEventArgs e)
//{
// if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != Gv2.EditIndex)
// {
// (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
// }
//}
protected void Gv2_RowEditing(object sender, GridViewEditEventArgs e)
{
Gv2.EditIndex = e.NewEditIndex;
this.BindGrid();
fillgridview2();
}
protected void Gv2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
Gv2.EditIndex = -1;
this.BindGrid();
fillgridview2();
}
protected void Gv2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = Gv2.Rows[e.RowIndex];
int tableId = Convert.ToInt32(Gv2.DataKeys[e.RowIndex].Values[0]);
string benefited_leaves = (row.FindControl("txtName") as TextBox).Text;
string basicallowance = (row.FindControl("txtCountry") as TextBox).Text;
using (hospitalEntities ctx = new hospitalEntities())
{
mann customer = (from c in ctx.manns
where c.tbl_id == tableId
select c).FirstOrDefault();
customer.benefited_leaves1 = benefited_leaves;
customer.basic_allowance1 = basicallowance;
ctx.SaveChanges();
}
Gv2.EditIndex = -1;
fillgridview2();
this.BindGrid();
}
protected void Gv2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int tableId = Convert.ToInt32(Gv2.DataKeys[e.RowIndex].Values[0]);
using (hospitalEntities ctx = new hospitalEntities())
{
mann customer = (from c in ctx.manns
where c.tbl_id == tableId
select c).FirstOrDefault();
ctx.Entry(customer).State = System.Data.Entity.EntityState.Deleted;
ctx.SaveChanges();
}
this.BindGrid();
}
}
}
aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm63.aspx.cs" Inherits="WebApplication14.WebForm63" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 1131px;
}
</style>
</head>
<body>
<form id="form1" runat="server" >
<asp:DropDownList DataTextField="benefited_leaves1" DataValueField="benefited_leaves1" ID="dd3" runat="server" ></asp:DropDownList>
<asp:TextBox ID="tb_allowance" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
<%-- <asp:GridView runat="server" ID="Gv2" DataKeyNames="tbl_id"
CellPadding="4" ForeColor="#333333" Width="90%" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="benefited_leaves1" HeaderText="Benefited Leaves" />
<asp:BoundField DataField="basic_allowance1" HeaderText="Basic Allowance" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>--%>
<asp:GridView runat="server" ID="Gv2" DataKeyNames="tbl_id" OnRowEditing="Gv2_RowEditing"
OnRowCancelingEdit="Gv2_RowCancelingEdit" OnRowUpdating="Gv2_RowUpdating" OnRowDeleting="Gv2_RowDeleting"
CellPadding="4" ForeColor="#333333" Width="90%" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="benefited leaves" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("benefited_leaves1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<%-- <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("benefited_leaves1") %>'></asp:TextBox>--%>
<asp:DropDownList runat="server" ID="dd31" DataTextField="benefited_leaves1" DataValueField="benefited_leaves1"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Basic Allowance" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("basic_allowance1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("basic_allowance1") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
Contributor
2110 Points
674 Posts
Re: in foreach dropdownlist not read items error occur objectreference not set?
Jun 17, 2020 07:00 AM|XuDong Peng|LINK
Hi, prabhjot1313
Based on the code you provided, I created a demo and modified the code.
If you break the point and run the program at the corresponding position, the issues you encountered may be like this:
The reason for this issues is that only when you click the Edit button will a DropDownList be generated in the corresponding row. DropDownList does not exist in other rows of GridView.
You could make some modifications to the code to meet your needs, please refer below code:
Result:
Hope this can help you.
Best regards,
Xudong Peng