我的DataGridView的某些列是从数据库加载的。此外,我手动向DataGridView添加了一些列。我想为第一列中名为“S_No”的每个单元格增加值。
我希望代码能澄清我的问题:
private void bindgrid()
{
dataGridView1.ColumnCount = 12;
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
string dtp = dateTimePicker3grd.Value.ToString("dd/MM/yyyy");
string query = "select s_no,Employee_id,Employee_name from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "') order by S_No ";
SqlCommand cmd = new SqlCommand(query, cn);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.Columns[0].Name = "S_No";
dataGridView1.Columns[0].HeaderText = "S_No";//*Here I Want to increment cell value by 1 for every cell..and the first cell of the column should be the last serial value of database*
dataGridView1.Columns[1].HeaderText = "Employee_id";
dataGridView1.Columns[1].Name = "Employee_Id";
dataGridView1.Columns[1].DataPropertyName = "Employee_id";
dataGridView1.Columns[2].Name = "Employee_name";
dataGridView1.Columns[2].HeaderText = "Employee_Name";
dataGridView1.Columns[2].DataPropertyName = "Employee_name";
dataGridView1.Columns[3].Name = "In_time";
dataGridView1.Columns[3].HeaderText = "In_time";
dataGridView1.Columns[4].Name = "Out_time";
dataGridView1.Columns[4].HeaderText = "Out_time";
dataGridView1.Columns[5].Name = "Date";
dataGridView1.Columns[5].HeaderText = "Date";
dataGridView1.Columns[6].Name = "Week_no_of_the_Month";
dataGridView1.Columns[6].HeaderText = "Week_no_of_the_Month";
dataGridView1.Columns[7].HeaderText = "Attendance";
dataGridView1.Columns[7].Name = "Attendance";
dataGridView1.Columns[8].HeaderText = "Image_of_the_Employee";
dataGridView1.Columns[8].Name = "Image_of_the_Employee";
dataGridView1.Columns[9].Name = "Image_path";
dataGridView1.Columns[9].HeaderText = "Image_path";
dataGridView1.Columns[10].Name = "Work_status";
dataGridView1.Columns[10].HeaderText = "Work_status";
dataGridView1.Columns[11].Name = "Remarks";
dataGridView1.Columns[11].HeaderText = "Remarks";
dataGridView1.DataSource = dt;
}
}
}
答案 0 :(得分:1)
在您的代码中,在行sda.Fill(dt);
之后添加以下代码行。请检查这是否适合您。稍后您可以添加异常检查,无论您是否从查询中获取记录。
int maxSlNo = int.Parse(dt.Rows[dt.Rows.Count - 1]["s_no"].ToString());
maxSlNo++;
foreach (DataRow dtRow in dt.Rows)
{
dtRow["s_no"] = maxSlNo;
maxSlNo++;
}
dt.AcceptChanges();
另外,添加以下行:
dataGridView1.Columns[0].DataPropertyName = "s_no";