Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
Hey i have an exception in the following code , i can't understand why the exception exists...


C#
con.Open();

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand("select * from mytable where ID=" + Convert.ToInt32(textBox3.Text.ToString()), con);

            DataTable dt = new DataTable();
            da.Fill(dt);


// Till now all is working well ...
            dataGridView1.DataSource = dt.DefaultView;


// Here i got the exception :(


dt.Rows[0].BeginEdit();

            dt.Rows[0][0] = Convert.ToInt32(textBox3.Text.ToString());
            dt.Rows[0][1] = textBox4.Text.ToString();

            dt.Rows[0].EndEdit();

            SqlCommandBuilder cb = new SqlCommandBuilder(da);


            da.Update(dt);

            con.Close();


[Edit]Code block added[/Edit]
Posted
Updated 2-Nov-12 6:30am
v2
Comments
[no name] 2-Nov-12 12:29pm    
Check if your dataGridView1 is null before you do a .DataSource, it might need to be initialized
SaadZulfiqar 2-Nov-12 12:35pm    
dataGridView is working fine infact the row is shown in the grid view but than there cpmes exception at
dt.Rows[0].BeginEdit();
[no name] 2-Nov-12 13:46pm    
other option is to do an AcceptChanges(), to the datatable
Thomas Daniels 2-Nov-12 12:30pm    
And in which row throws the error?
The first error after the "Here i got the exception :(" comment line?
SaadZulfiqar 2-Nov-12 12:36pm    
dataGridView is working fine infact the row is shown in the grid view but than there cpmes exception at
dt.Rows[0].BeginEdit();

Look at your database - you have no rows with an ID matching the value in Textbox3.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Nov-12 17:48pm    
Sure, a 5.
--SA
There is no row at position 0. and it comes at dt.Rows[0].BeginEdit();
This simply means that there are no records in the table. It's empty.

For edit feature in grid, have a look at these articles:
Inplace Edit in GridView[^]

Simple ADO.NET Database Read, Insert, Update and Delete using C#[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Nov-12 17:49pm    
Sure, a 5.
--SA
That error will occur because you aren't checking to make sure you have rows in your data table before using it. You should always check to make sure things exist before trying to use them.
C#
if( dt.Rows.Count > 0 )
{
   // ... Now do your stuff with it.
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Nov-12 17:48pm    
Sure, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900