【问题标题】:How to save the checked row in gridview to sql database如何将gridview中选中的行保存到sql数据库
【发布时间】:2013-12-30 07:59:04
【问题描述】:

我使用GridView,作为第一列我有一个CheckBox - 通过选择这个CheckBox,它的行应该被保存到数据库中:

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 中的检查项目...

【问题讨论】:

    标签: c# winforms gridview


    【解决方案1】:

    这里是您的问题的解决方案:

    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;
        }
    }
    

    实际上,row.Cell[0] 缺少 .Value,因此在变量 c 中将保留 DataGridViewCheckBoxCell,而不是包含值。

    【讨论】:

    • c=row.Cells[0].value.,而不是这个代码,我可以使用 c=row.Rows[].Cells[0].value
    • @Sarvan 它看起来不错,你用这段代码替换了你的完整代码吗? Cell[0] 具有 .Value 属性。为什么要在foreach 中使用索引i 看?
    • 无法将类型“object”隐式转换为“System.Windows.Forms.DataGridViewCell”。存在显式转换(您是否缺少演员表?)
    • @Sarvan 好的,知道了,我想你用 DataGridViewCell 声明了你的变量 c,对吧?检查编辑的代码。
    • @AnkushMadankar:你也可以写成c.Value = _value != null && !(bool)_value +1。请不要要求投票兄弟......
    【解决方案2】:

    试试这个,

    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");
            }
    

    【讨论】:

    • 你好 ZEY。,但这里 chk 只显示所有时间 TRUE。,也适用于未选中的行。,
    【解决方案3】:

    您将foreach 循环与for 循环混合使用。应该是:

    foreach (DataGridViewRow row in grid_stock.Rows)
    {
        c = row.Cells[0];
        // ...
    }
    

    【讨论】:

    • 你好,我想在gridview中检查,哪些行被检查用于检查目的,只有我正在使用FOREACH循环。
    • 好的。像我写的那样使用它。更好的方法是使用FindControl() 来确定复选框值。
    【解决方案4】:
     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++;
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 2015-04-10
      • 2019-03-31
      • 2013-02-04
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多