One way I tried to do this and works fine, might need some modifications
SetValue = Marriage.SetValue;
cmbcount = Marriage.cmbcount;
DataRow dr;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[dbConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand comd = new SqlCommand();
comd.CommandType = CommandType.StoredProcedure;
comd.CommandText = "usp_CAMR_BatchVerify";
con.Open();
comd.Connection = con;
comd.Parameters.AddWithValue("@BATCH_NAME", SetValue);
comd.Parameters.AddWithValue("@ERR_CODE","");
comd.Parameters.AddWithValue("@ERR_MSG", "");
comd.Parameters.AddWithValue("@TABLE_NAME", "");
SqlDataAdapter sda1 = new SqlDataAdapter(comd);
DataTable dt1 = new DataTable();
dt1.Columns.Add("A");
dt1.Columns.Add("B");
dt1.Columns.Add("C");
dt1.Columns.Add("D");
dt1.Columns.Add("E");
dt1.Columns.Add("F");
dt1.Columns.Add("G");
dt1.Columns.Add("H");
dt1.Columns.Add("I");
dt1.Columns.Add("J");
dt1.Columns.Add("K");
SqlDataReader dr1 = comd.ExecuteReader();
int i1 = 1;
while (dr1.Read())
{
for (int i3 = i1; i3 <= cmbcount; i3++)
{
DataRow dr01 = dt1.NewRow();
setimg = dr1["field1"].ToString();
string tempimg = setimg.Substring(3, 4);
tmpimg = Convert.ToInt32(tempimg);
/* fields to be entered into dt1
as dr01["A"] = dr1["A"]*/
if (i1 == tmpimg)
{
//to add rows from database
dt1.Rows.Add(dr01);
i1++;
}
else
{
// to add missing rows between the rows from the database
for (int i = i1; i < tmpimg; i++)
{
dr01 = dt1.NewRow();
dt1.Rows.Add(dr01);
dt1.AcceptChanges();
dataGridView1.DataSource = dt1;
i1++;
}
}
}
dataGridView1.DataSource = dt1;
}
// to add rows at the end
for (int i = dt1.Rows.Count; i < cmbcount; i++)
{
dr = dt1.NewRow();
dt1.Rows.Add(dr);
}
dt1.AcceptChanges();
dataGridView1.DataSource = dt1;
}