Hello,
this is my code for binding the gridView:
- public void bindGrid(GridView gv, String id)
- {
- DataSet ds;
- SqlDataAdapter SqlAda;
- SqlConnection con =getConnection();
- SqlCommand cmd = new SqlCommand();
-
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.CommandText = "sproc";
- cmd.Parameters.Add("@id", SqlDbType.VarChar).Value =id;
- cmd.Connection = con;
- try
- {
- con.Open();
- gv.EmptyDataText = No data";
-
- SqlAda = new SqlDataAdapter(cmd);
- ds = new DataSet();
-
- SqlAda.Fill(ds);
-
- gv.DataSource = ds;
- gv.DataBind();
- }
- catch (Exception ex)
- {
- myMessageBox(ex.Message);
- }
- finally
- {
- con.Close();
- con.Dispose();
- }
- }
It works ok until I added a dropdownlist on the gridview. I' m loading the ddl using the following code:
- protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- DropDownList ddlTypes = (e.Row.FindControl("ddlType") as DropDownList);
- fillDDL(ddlTypes, "sproc", "ID", "TypeDescr", "");
-
- string myType = (e.Row.FindControl("lblType") as Label).Text;
- ddlTypes.Items.FindByValue(myType).Selected = true;
- }
- }
- private void fillDDL(DropDownList ddl, string sproc, string code, string description, string headertext)
- {
- DataTable dt = new DataTable();
- SqlConnection connection = appObj.getConnection();
-
- ddl.Items.Clear();
- ddl.Items.Add(new ListItem(headertext, "0"));
-
- ddl.AppendDataBoundItems = true;
- try
- {
- connection.Open();
-
- SqlCommand sqlCmd = new SqlCommand(sproc, connection);
- SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
- sqlCmd.CommandType = CommandType.StoredProcedure;
-
- sqlDa.Fill(dt);
-
-
- if (dt.Rows.Count > 0)
- {
-
- ddl.DataSource = dt;
- ddl.DataTextField = description;
- ddl.DataValueField = code;
- ddl.DataBind();
- }
- }
- catch (Exception ex)
- {
- HttpContext.Current.Session["error"] = ex.Message.ToString();
- HttpContext.Current.Response.Redirect("Error.aspx");
- }
- finally
- {
- connection.Close();
- }
- }
and the .aspx page
- <asp:TemplateField HeaderText="Type" Visible="false">
- <ItemTemplate>
- <asp:Label ID="lblType" runat="server" Text='<%#Eval("TypeDescr") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:Label ID="lblValue" runat="server" Text='<%#Eval("TypeID") %>' Visible="true"></asp:Label>
- <asp:DropDownList ID="ddlType" runat="server"></asp:DropDownList>
- </EditItemTemplate>
- </asp:TemplateField>
The problem is on loading I get the error "Object Reference not set to an instance of an object". The dropdownlist is loading with values, but cannot get assigned value.
Any kind of help would be appreciated.
Thank you in advance.