Hi,
If your exception is getting raised on line 13, then it looks like either:
1) your datatable does not contain the number of columns you are expecting. i.e. - your datatable does not contain more that 1 column.
2) Your DataGridView control does not contain the number of columns youare expecting.
I've amended your code to add a couple of basic checks, that will avoid this type of exceptions being thrown.
The 1st one is:
if (ds.Tables.Count > 0)
... this checks you have a datatable.
The 2nd one is:
if (ds.Tables[0].Columns.Count > 6)
... this checks your datatable contains the amount of columns you are expecting.
The 3rd one is:
if(dgv_EmpBonusList.ColumnCount>6)
... this checks your datagridview control contained the amount of columns you are expecting.
This will not resolve your issue of the number of columns being less that expected, but it will avoid the exception begin thrown.
private void frmEmpBonusList_Load(object sender, EventArgs e)
{
dgv_EmpBonusList.AutoGenerateColumns = false;
da = new SqlDataAdapter("Select docno,docdate,BonusName,BonusType,minSalary,maxSalary,PerAmount from EmpBonus order by docno,minsalary", constring);
try
{
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
{
dgv_EmpBonusList.DataSource = ds.Tables[0];
if ((ds.Tables[0].Columns.Count > 6)&&(dgv_EmpBonusList.ColumnCount>6))
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dgv_EmpBonusList.ReadOnly = true;
dgv_EmpBonusList.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i][0].ToString();
dgv_EmpBonusList.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i][1].ToString();
dgv_EmpBonusList.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i][2].ToString();
dgv_EmpBonusList.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i][3].ToString();
dgv_EmpBonusList.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i][4].ToString();
dgv_EmpBonusList.Rows[i].Cells[5].Value = ds.Tables[0].Rows[i][5].ToString();
dgv_EmpBonusList.Rows[i].Cells[6].Value = ds.Tables[0].Rows[i][6].ToString();
cmgr = (CurrencyManager)dgv_EmpBonusList.BindingContext[ds.Tables[0]];
this.dgv_EmpBonusList.EnableHeadersVisualStyles = false;
this.dgv_EmpBonusList.ColumnHeadersHeight = 20;
this.dgv_EmpBonusList.BackgroundColor = Color.LightBlue;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
da.Dispose();
}
}
... hope it helps.