Reputation: 81
html code:
<ItemTemplate>
<asp:Literal ID="faculty" runat="server" Text='<%#Eval("facultyname")%>'>
</asp:Literal>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="fact" runat="server">
</asp:DropDownList>
code bihind:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
DropDownList dropdown = GridView1.Rows[e.NewEditIndex].FindControl("fact") as DropDownList;
facultyDal c = new facultyDal();
dropdown.DataSource = c.show();
dropdown.DataBind();
dropdown.DataTextField = "facultyname";
dropdown.DataValueField = "facultyid";
}
Exception:
Object reference not set to an instance of an object.
When i bind to dropdown with datasource the above exception occur please help....
Upvotes: 0
Views: 8600
Reputation: 1
The error coming because of you trying to bind data to dropdown list before edit mode enable.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gridbind();//fetch data from database and bind to grid
DropDownList dropdown = GridView1.Rows[e.NewEditIndex].FindControl("fact") as DropDownList;
facultyDal c = new facultyDal();
dropdown.DataSource = c.show();
dropdown.DataBind();
dropdown.DataTextField = "facultyname";
dropdown.DataValueField = "facultyid";
}
Upvotes: 0
Reputation: 12709
change your code to following
GridView1.EditIndex
DropDownList dropdown = GridView1.Rows[GridView1.EditIndex].FindControl("fact") as DropDownList;
Upvotes: 0
Reputation: 64
using grid view rowdatabound evet we can bind the data to web control in grid view
get row and find the control using edit index then bind data
Upvotes: 0
Reputation: 11
Try like this using RowDataBound.
For Binding in editmode
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
{
DropDownList ddlfaculties = (DropDownList)e.Row.FindControl("fact");
string query = "select distinct facultyname from your-Table-Name";
SqlCommand cmd = new SqlCommand(query);
ddlfaculties .DataSource = GetData(cmd);
ddlfaculties .DataTextField = "facultyname";
ddlfaculties .DataValueField = "facultyid";
ddlfaculties .DataBind();
ddlfaculties .Items.FindByValue((e.Row.FindControl("faculty") as Literal).Text).Selected = true;
}
}
For uddating the selected value from dropdown list.
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
{
DropDownList ddlfaculties = (DropDownList)e.Row.FindControl("fact");
string query = "select distinct facultyname from Your-Table-Name";
SqlCommand cmd = new SqlCommand(query);
ddlfaculties .DataSource = GetData(cmd);
ddlfaculties .DataTextField = "facultyname";
ddlfaculties .DataValueField = "facultyid";
ddlfaculties .DataBind();
ddlfaculties .Items.FindByValue((e.Row.FindControl("faculty") as Literal).Text).Selected = true;
}
}
Upvotes: 1