基本上我的问题是我的代码似乎是跳过我的foreach循环,我的目的是从同一行点击按钮获取行值,这是我的代码到目前为止:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
string userID;
string Monday;
string Tuesday;
string Wednesday;
string Thursday;
string Friday;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
userID = row.Cells[0].Value.ToString();
Monday = row.Cells[1].Value.ToString();
Tuesday = row.Cells[2].Value.ToString();
Wednesday = row.Cells[3].Value.ToString();
Thursday = row.Cells[4].Value.ToString();
Friday = row.Cells[5].Value.ToString();
dbHandler objDBHandler = new dbHandler();
objDBHandler.writeDB("INSERT INTO [OfficeCalendar].[dbo].[DayData]([UserID],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday]) VALUES ('" + userID + "','" + Monday + "','" + Tuesday + "','" + Wednesday + "','" + Thursday + "','" + Friday + "');", "byron");
}
}
}
答案 0 :(得分:0)
我通过改变来修正自己的问题,
DataGridView的SelectionMode到FullRowSelect
对MethodMan的道具感谢它帮助了很多的评论答案 1 :(得分:0)
除非您允许用户一次选择多行,否则无需循环访问它们。 DataGridViewCellEventArgs
事件的CellContentClick
参数对象已经为您提供了点击的行号。
string userID;
string Monday;
string Tuesday;
string Wednesday;
string Thursday;
string Friday;
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
userID = row.Cells[0].Value.ToString();
Monday = row.Cells[1].Value.ToString();
Tuesday = row.Cells[2].Value.ToString();
Wednesday = row.Cells[3].Value.ToString();
Thursday = row.Cells[4].Value.ToString();
Friday = row.Cells[5].Value.ToString();
dbHandler objDBHandler = new dbHandler();
objDBHandler.writeDB("INSERT INTO [OfficeCalendar].[dbo].[DayData]([UserID],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday]) VALUES ('" + userID + "','" + Monday + "','" + Tuesday + "','" + Wednesday + "','" + Thursday + "','" + Friday + "');", "byron");
此外,在偏离主题的情况下,您的代码会提示进行SQL注入;使用参数化查询而不是字符串连接。