C# 如何将gridview中选中的行保存到sql数据库
我使用的是C# 如何将gridview中选中的行保存到sql数据库,c#,winforms,gridview,C#,Winforms,Gridview,我使用的是网格视图,作为第一列,我有一个复选框——通过选择此复选框,它的行应保存到数据库中: foreach (DataGridViewRow row in grid_stock.Rows) { c = grid_stock.Rows[i].Cells[0]; b = c.EditedFormattedValue == null ? false : bool.Parse(c.EditedFormattedValue.ToString()); if (b != true)
网格视图
,作为第一列,我有一个复选框
——通过选择此复选框
,它的行应保存到数据库中:
foreach (DataGridViewRow row in grid_stock.Rows)
{
c = grid_stock.Rows[i].Cells[0];
b = c.EditedFormattedValue == null ? false : bool.Parse(c.EditedFormattedValue.ToString());
if (b != true)
{
c.Value = true;
//here i am inserting the data to sql.,
}
else
{
c.Value=false;
}
}
但是这里我没有进入循环,它没有正确地检查GridView中的已检查项…您将
foreach
循环与for
循环混合在一起。应该是:
foreach (DataGridViewRow row in grid_stock.Rows)
{
c = row.Cells[0];
// ...
}
试试这个
foreach (DataGridViewRow row in grid_stock.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
chk.Value = !(chk.Value == null ? false : (bool) chk.Value);
}
或者你可以通过这种方式得到你的支票价值
if (Convert.ToBoolean(chk.Value) == true)
{
MessageBox.Show("Value Is True");
}
以下是您问题的解决方案:
foreach (DataGridViewRow row in grid_stock.Rows)
{
var _value = row.Cells[0].Value;
if (_value != null && !(bool)_value)
{
c.Value = true;
//here i am inserting the data to sql.,
}
else
{
c.Value = false;
}
}
实际上,您在
行中缺少.Value
。单元格[0]
,因此在变量c
中,将保留DataGridViewCheckBoxCell
,而不是Value contain。您好,我想在gridview中进行检查,这些行仅用于检查目的。我正在使用InMg FOREACH循环。Ok。像我写的那样使用它。更好的方法是使用FindControl()
来确定复选框值。Hello ZEY.,但这里chk仅显示所有时间为TRUE。对于未选中的行,也可以使用c=row.Cells[0].value.,而不是此代码,我可以使用c=row.rows[].Cells[0]。value@Sarvan它看起来不错,你用这个代码替换了你的完整代码了吗?单元格[0]具有.Value
属性。为什么要在foreach
look中使用indexi
?无法将类型“object”隐式转换为“System.Windows.Forms.DataGridViewCell”。存在显式转换(是否缺少转换?@Sarvan好的,明白了,我认为您使用DataGridViewCell声明了变量c
,对吗?检查编辑过的代码。@AnkushMadankar:您也可以将其写成c.Value=\u Value!=空&!(bool)\ u值
+1。请不要向上要求投票,兄弟。。。
int j = 0;
foreach (DataGridViewRow row in grid_stock.Rows)
{
bool vc = Convert.ToBoolean(grid_stock.Rows[j].Cells[0].Value);
if (vc == true)
{
//Here my inserting to sql db
j++;
}
}
else
{
j++;
}