Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过DataReader将选定字段中的值添加到DataGridView_C#_Database_Datagridview - Fatal编程技术网

C# 如何通过DataReader将选定字段中的值添加到DataGridView

C# 如何通过DataReader将选定字段中的值添加到DataGridView,c#,database,datagridview,C#,Database,Datagridview,我是C语言的新手。我想将表的选定字段中的数据添加到DataGridView。我用的是数据阅读器。执行时只添加一行。while循环的第二次出现错误,因为提供的行已属于DataGridView控件。这是我的密码。任何人都可以帮忙 public static void fillGrd(ref DataGridView obj, string tbl, string fld="*", string cond = "") { try {

我是C语言的新手。我想将表的选定字段中的数据添加到DataGridView。我用的是数据阅读器。执行时只添加一行。while循环的第二次出现错误,因为提供的行已属于DataGridView控件。这是我的密码。任何人都可以帮忙

        public static void fillGrd(ref DataGridView obj, string tbl, string fld="*", string cond = "")
    {
        try
        {
            obj.Rows.Add();
            DataGridViewRow row = (DataGridViewRow)obj.Rows[0].Clone();
            obj.Rows.Clear();
            cond = (cond == "") ? cond : " where " + cond;
            string qry = "select " + fld+ " from " + tbl + cond;
            cmd.CommandText = qry;
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                int ri = 0;
                while (dr.Read())
                {
                    for (int i = 0; i < dr.FieldCount - 1; i++)
                    {
                        row.Cells[i].Value = dr.GetString(i);
                    }
                    obj.Rows.Insert(ri,row);
                    ri++;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error occured!" + ex.Message);
        }
    }

移动此DataGridViewRow行=DataGridViewRowobj.Rows[0]。克隆;在while的内部。为什么不使用DataAdapter来填充数据表而不是使用读卡器呢?从代码中,您没有对每一行的数据进行任何处理。您每次都尝试添加同一行,这是不允许的。因此,您需要为每个reader.read创建一个新的reader.read,可以按照Gusman的建议进行克隆,也可以简单地通过int ix=obj.Rows.Add1;然后填充字段…@TruthSeeker我已经尝试过了,但没有效果。