GridView: Binding Database Fields to Textboxes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MiziaQ
    New Member
    • Nov 2007
    • 63

    GridView: Binding Database Fields to Textboxes

    I am connecting to a database table to pass values to textboxes in a gridview. I get the following error:

    Object reference not set to an instance of an object.

    Thanks in advance for your help!

    Code:
    private void ReadProjects()
        {
    
            SqlDataReader rdr;
    
            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    
            SqlCommand cmd = new SqlCommand("SELECT * FROM Projects", conn);
    
            cmd.CommandType = CommandType.Text;
    
            int rowIndex = 0;
    
            if (ViewState["CurrentTable"] != null)
            {
    
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow dr = null;
    
                if (dtCurrentTable.Rows.Count > 0)
                {
    
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
    
                        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("project_name");
                        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("project_manager");
                        TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("team_members");
                        TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("status");
    
                        using (conn)
                        {
                            //open connection
                            conn.Open();
    
                            rdr = cmd.ExecuteReader();
    
                            while (rdr.Read())
                            {
                                dr = dtCurrentTable.NewRow();
    
                                box1.Text = rdr["ProjectName"].ToString();
                                box2.Text = rdr["ProjectID"].ToString();
                                box3.Text = rdr["CompanyID"].ToString();
                                box4.Text = rdr["Description"].ToString();
    
                                dtCurrentTable.Rows.Add(dr);
    
                                dtCurrentTable.AcceptChanges();
                            }
                        }
    
                        rowIndex++;
    
                    }
    
                    ViewState["CurrentTable"] = dtCurrentTable;
    
    
                }
    
           }
    
            else
            {
    
                Response.Write("ViewState is null");
    
            }
    
        }
    }
Working...