-1

I have gridview using asp.net with c# . It show data of table in sql server . When I updated certain row I got this message: Object reference not set to an instance of an object.
I tried many codes, but non worked .. can you help me to figure out this problem. Thanks.

This is gridview code

       <asp:GridView ID="gvIqamaAlert" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="EmpNo" onrowcancelingedit="gvIqamaAlert_RowCancelingEdit" 
            onrowediting="gvIqamaAlert_RowEditing" onrowupdating="gvIqamaAlert_RowUpdating" 
            Width="828px">
            <Columns>
                <asp:BoundField DataField="Nationality" HeaderText="الجنسيه" ReadOnly="True" 
                    SortExpression="Nationality" />
                <asp:TemplateField ControlStyle-BorderStyle="NotSet" 
                    HeaderText="تاريخ الميلاد الهجري">
                    <EditItemTemplate>
                        <asp:Label ID="Label21" runat="server" 
                            Text='<%# GetHijri(String.Format("{0:dd-MM-yyyy}", Eval("DOB"))) %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" 
                            Text='<%# GetHijri(String.Format("{0:dd-MM-yyyy}", Eval("DOB"))) %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="تاريخ الميلاد" SortExpression="DOB">
                    <EditItemTemplate>
                        <asp:Label ID="Label11" runat="server" 
                            Text='<%# String.Format("{0:dd-MM-yyyy}", Eval("DOB")) %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" 
                            Text='<%# String.Format("{0:dd-MM-yyyy}", Eval("DOB")) %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="جهة الاصدار" SortExpression="IDIssPlace">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtIssP" runat="server" Text='<%# Eval("IDIssPlace") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Eval("IDIssPlace") %>'></asp:Label>
                    </ItemTemplate>


                <asp:TemplateField HeaderText="الاسم" SortExpression="FName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtfname" runat="server" Text='<%# Eval("FName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label6" runat="server" Text='<%# Eval("FName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="الرقم الوظيفي">
                <EditItemTemplate>
                        <asp:Label ID="Labe1" runat="server" Text='<%# Eval("EmpNo") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("EmpNo") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
<asp:TemplateField>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lbtnUpdate" RunAt="server" CommandName="Update" 
                            Text="موافق" />
                        <asp:LinkButton ID="lbtnCancel" RunAt="server" CommandName="Cancel" 
                            Text="الغاء" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbtnEdit" RunAt="server" CommandName="Edit" Text="تعديل" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView> 

Code Behind:

private SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=dbHrSys;Integrated Security=True");

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindEmployeeDetails();
    }
}
protected void BindEmployeeDetails()
{
    con.Open();
    SqlCommand cmd = new SqlCommand(" Select IDNo, EmpNo, Nationality, IDIssDate, IDExpDate, IDIssPlace, FName, DOB, Flag FROM Employee WHERE (IDExpDate <= DATEADD(day, 30, GETDATE())) AND (Flag = 2)", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    if (ds.Tables[0].Rows.Count > 0)
    {
        gvIqamaAlert.DataSource = ds;
        gvIqamaAlert.DataBind();
    }
    else
    {
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
        gvIqamaAlert.DataSource = ds;
        gvIqamaAlert.DataBind();
        int columncount = gvIqamaAlert.Rows[0].Cells.Count;
        gvIqamaAlert.Rows[0].Cells.Clear();
        gvIqamaAlert.Rows[0].Cells.Add(new TableCell());
        gvIqamaAlert.Rows[0].Cells[0].ColumnSpan = columncount;
        gvIqamaAlert.Rows[0].Cells[0].Text = "No Records Found";
    }

}

protected void gvIqamaAlert_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvIqamaAlert.EditIndex = e.NewEditIndex;
    BindEmployeeDetails();
}

protected void gvIqamaAlert_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label l = (Label)gvIqamaAlert.Rows[e.RowIndex].FindControl("Label1");

    string jobId = gvIqamaAlert.DataKeys[e.RowIndex].Value.ToString();
    TextBox fname = (TextBox)gvIqamaAlert.FindControl("txtfname");
    TextBox IssP = (TextBox)gvIqamaAlert.FindControl("txtIssP");
    ////TextBox Issd = (TextBox)gvIqamaAlert.FindControl("txtIssd");
    ////temp1 = ((TextBox)gvIqamaAlert.FindControl("txtIssd")).Text;
    //DateTime Iss = DateTime.ParseExact(Greg(((TextBox)gvIqamaAlert.FindControl("txtIssd")).Text), "dd/MM/yyyy", null);
    //TextBox Expd = (TextBox)gvIqamaAlert.FindControl("txtExpd");
    //temp2 = Greg(Expd.ToString());
    //DateTime Exp = DateTime.ParseExact(temp2, "dd/MM/yyyy", null);

    con.Open();

    SqlCommand cmd = new SqlCommand("Update Employee set FName='" + fname.Text + "',IDIssPlace='" + IssP.Text + "' where EmpNo='" + Convert.ToString(l.Text) + "'", con);
    cmd.Parameters.AddWithValue("@id", jobId);
    //,IDIssDate = @iss, IDExpDate = @exp
    //cmd.Parameters.AddWithValue("@iss",Iss);
    //cmd.Parameters.AddWithValue("@exp", Exp);
    cmd.ExecuteNonQuery();
    con.Close();

    gvIqamaAlert.EditIndex = -1;
    BindEmployeeDetails();
}

protected void gvIqamaAlert_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvIqamaAlert.EditIndex = -1;
    BindEmployeeDetails();
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • In which line you are getting this exception? – Emad Mokhtar Dec 29 '13 at 11:55
  • in this code:SqlCommand cmd = new SqlCommand("Update Employee set FName='" + fname.Text + "',IDIssPlace='" + IssP.Text + "' where EmpNo='" + Convert.ToString(l.Text) + "'", con); – user3040759 Dec 29 '13 at 12:35
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Dec 29 '13 at 13:03
  • I still have problem :( – user3040759 Dec 29 '13 at 13:19

5 Answers5

1

I was getting null because of this code

TextBox fname = (TextBox)gvIqamaAlert.FindControl("txtfname");
TextBox IssP = (TextBox)gvIqamaAlert.FindControl("txtIssP");

.Rows[e.RowIndex] was missing. The new code :

TextBox fname = (TextBox)gvIqamaAlert.Rows[e.RowIndex].FindControl("txtfname");
TextBox IssP = (TextBox)gvIqamaAlert.Rows[e.RowIndex].FindControl("txtIssP");

Now It's working well. Thanks for your help .

0

Try using the following code to get the EmpNO:

int ro = gvr.RowIndex; 
string EmpNO = gvDetails.DataKeys[ro].Value.ToString();

instead of this one:

Label l = (Label)gvIqamaAlert.Rows[e.RowIndex].FindControl("Label1");

Then change the SQL command to the following:

SqlCommand cmd = new SqlCommand("Update Employee set FName='" + fname.Text + "',IDIssPlace='" + IssP.Text + "' where EmpNo='" + EmpNO + "'", con);
Laila
  • 417
  • 1
  • 3
  • 14
  • 1
    int ro = gvr.RowIndex; I got this error : Error 4 'System.Web.UI.WebControls.GridView' does not contain a definition for 'RowIndex' and no extension method 'RowIndex' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found (are you missing a using directive or an assembly reference?) C:\Users\Menoo\Desktop\Dec5 V2\Dec5 V2\Dec5 2013\HR System v1\Alertpage.aspx.cs – user3040759 Dec 29 '13 at 12:59
0

Please replce following code with mention code:

  protected void gvIqamaAlert_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {

    Label l = (Label)gvIqamaAlert.Rows[e.RowIndex].FindControl("Label1");
    string jobId = gvIqamaAlert.DataKeys[e.RowIndex].Value.ToString();
    TextBox fname = (TextBox)gvIqamaAlert.FindControl("txtfname");
    TextBox IssP = (TextBox)gvIqamaAlert.FindControl("txtIssP");

    if(l == null || fname == null || IssP == null) return;

    ////TextBox Issd = (TextBox)gvIqamaAlert.FindControl("txtIssd");
    ////temp1 = ((TextBox)gvIqamaAlert.FindControl("txtIssd")).Text;
    //DateTime Iss = DateTime.ParseExact(Greg(((TextBox)gvIqamaAlert.FindControl("txtIssd")).Text), "dd/MM/yyyy", null);
    //TextBox Expd = (TextBox)gvIqamaAlert.FindControl("txtExpd");
    //temp2 = Greg(Expd.ToString());
    //DateTime Exp = DateTime.ParseExact(temp2, "dd/MM/yyyy", null);

    con.Open();

    SqlCommand cmd = new SqlCommand("Update Employee set FName='" + fname.Text + "',IDIssPlace='" + IssP.Text + "' where EmpNo='" + Convert.ToString(l.Text) + "'", con);
    cmd.Parameters.AddWithValue("@id", jobId);
    //,IDIssDate = @iss, IDExpDate = @exp
    //cmd.Parameters.AddWithValue("@iss",Iss);
    //cmd.Parameters.AddWithValue("@exp", Exp);
    cmd.ExecuteNonQuery();
    con.Close();

    gvIqamaAlert.EditIndex = -1;
    BindEmployeeDetails();
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
Ankush Madankar
  • 3,689
  • 4
  • 40
  • 74
  • I did. this code if(l == null || fname == null || IssP == null) return; has the value null with all conditions. Now, I'm trying to figure out why my code doesn't get the values correctly . – user3040759 Dec 30 '13 at 06:11
  • @user3040759 Then please check it, why label `l`, `fname` and `IssP` not getting values. Adding null check only handle exception not ur base problem! – Ankush Madankar Dec 30 '13 at 06:16
0

The problem is you're trying to find controls in GridView without passing the Row index

TextBox fname = (TextBox)gvIqamaAlert.FindControl("txtfname");
TextBox IssP = (TextBox)gvIqamaAlert.FindControl("txtIssP");

Try to pass the Row Index like what you've done in Label1

 Label l = (Label)gvIqamaAlert.Rows[e.RowIndex].FindControl("Label1");

To be like this:

TextBox fname = (TextBox)gvIqamaAlert.Rows[e.RowIndex].FindControl("txtfname");
TextBox IssP = (TextBox)gvIqamaAlert.Rows[e.RowIndex].FindControl("txtIssP");
Emad Mokhtar
  • 3,237
  • 5
  • 31
  • 49
0

Row Editing: When user clicks on edit button and row editing event of grid view will be executed.This event will provide row index

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        databind();
    }

Row Updating: This will perform post back,row-updating event procedure of grid view will be executed

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label l = (Label)GridView1.Rows[e.RowIndex].FindControl("Label1");
        TextBox t1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
        TextBox t2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
        FileUpload fu = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");

        string fpath = Server.MapPath("images");
        string fname = fu.FileName;
        string concat = fpath + "\\" + fname;
        fu.SaveAs(concat);

        cmd = new SqlCommand("update userdata set username='" + t1.Text + "', password='" + t2.Text + "' , Image = '" + "~/images/"+ fu.FileName + "' where userid='" + Convert.ToInt32(l.Text) + "'", con);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        GridView1.EditIndex = -1;
        databind();
    }
Tejas
  • 467
  • 5
  • 13