How to overcome from the error
i m making add,edit delete module...For that i have the following code in the c#,
private void listOfCompany_Load(object sender, EventArgs e)
{
//MessageBox.Show(updID.ToString());
con.ConnectionString = @"PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany_1.mdb";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string sql = "SELECT * From tblCompany_1 WHERE ID="+updID;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
开发者_运维问答 da.Fill(ds);
// dataGridView1.DataSource = ds.Tables[0];
DataRow dr = ds.Tables[0].Rows.Count;
textBox1.Text = dr.ItemArray.GetValue(0).ToString();
textBox4.Text = dr.ItemArray.GetValue(2).ToString();
/* int t = ds.Tables[0].Columns.Count;
for (int i = 0; i < cnt; i++)
{
dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(0).ToString();
dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(1).ToString();
dataGridView1.Rows[i].Cells[2].Value = dr.ItemArray.GetValue(2).ToString();
}*/
}
when i debug the application, then on add,edit and delete button, it gives me error at the "DataRow dr = ds.Tables[0].Rows[0];" that "IndexOutOf RangeException was handled" and the error is "There is no row at position 0."...How should i overcome from this?
Well that suggests there's no record with that ID. You should check for that before going ahead and trying to use it. You can use ds.Tables[0].Rows.Count
to find out how many rows were returned.
You should also start using parameterized queries instead of including values directly within the SQL statement you're building, in order to avoid SQL injection attacks. If the ID is an integer then it probably isn't a problem here, but generally parameterized SQL queries are the way forward.
How about:
DataRow dr;
for(int i = 0; i<ds.Tables.Count; i++){
for(int j = 0; j<ds.Tables[i].Rows.Count; j++){
dr = ds.Tables[i].Rows[j];
//Do something with dr.
}
}
Note: It is possibly "Length" in stead of "Count". Can't remember right now:p
精彩评论