【问题标题】:fetching data in datagridview in C#在 C# 中的 datagridview 中获取数据
【发布时间】:2014-01-10 10:09:52
【问题描述】:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;


namespace testdb
{
    public partial class Form1 : Form
    {
        private string constr =
            @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =     C:/Users/Xprts_3/Documents/Database1.accdb";

        public Form1()
        {
            InitializeComponent();
            Bind();
        }

        private void Bind()
        {
            OleDbConnection con = new OleDbConnection(constr);
            OleDbCommand cmd = new OleDbCommand();

            cmd.Connection = con;
            cmd.CommandText = "select * from tb1";
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dataGridView1.Rows.Add(new DataGridViewRow());
                int j;
                for (j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    dataGridView1.Rows[i].Cells[j].Value = ds.Tables[0].Rows[i][j].ToString();
                }
            }

            con.Close();
        }
    }
}

这是我在DataGridView 中从数据库中获取数据的代码,但它显示了这个错误:

当控件是数据绑定时,不能以编程方式将行添加到 DataGridView 的行集合 在这一行:

dataGridView1.Rows.Add(new DataGridViewRow());

【问题讨论】:

标签: c# .net winforms


【解决方案1】:

Lucian 的回答是正确的,在这种情况下您应该使用 DataBind()。但是,如果您想以其他方式在 DataGridView 中添加行,这里有一个示例:

private void Bind()
{
    OleDbConnection con = new OleDbConnection(constr);
    OleDbCommand cmd = new OleDbCommand();

    cmd.Connection = con;
    cmd.CommandText = "select * from tb1";
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);


    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        var row = (DataGridViewRow)dataGridView1.Rows[0].Clone();

        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
        {
            row.Cells[j].Value = ds.Tables[0].Rows[i][j].ToString();
        }

        dataGridView1.Rows.Add(row);
    }

    con.Close();
}

未经测试,但我认为它应该可以工作。只评论结果。

【讨论】:

    【解决方案2】:

    更新答案:

    首先,您绝对应该将对数据库的调用与其余代码分开。让我们创建一个GetData() 方法来负责...获取数据:)

    private DataSet GetData(string constr) {
        //'using' constructs are always a good idea when dealing with database operations
        //your connection will automatically close
        using(OleDbConnection con = new OleDbConnection(constr)){
            using(OleDbCommand cmd = new OleDbCommand()){       
                cmd.Connection = con;
                cmd.CommandText = "select * from tb1";
                cmd.CommandType = CommandType.Text;
                OleDbDataAdapter da = new OleDbDataAdapter();
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
        }
    }
    

    然后绑定你的 DataGridView 你有两个选择:

    1. 使用DataBind() 方法
    2. 以编程方式创建网格列和行

    方法一 - DataBind() 方式:

    private void BindWithDataBind() {
        dataGridView1.DataSource = GetData();
        //call the databind method to bound the data to the grid
        //the grid structure will be created automatically from the datatable structure
        dataGridView1.DataBind(); 
    }
    

    方法 2 - 程序化方式

    private void BindProgramatically() {
    
        //obtain the data from your OleDB connection
        DataSet ds = GetData(constr);
        if(ds == null) {
            return;
        }
        DataTable dt = ds.Tables[0];
    
        //build the grid structure, add a new grid column for each datatable column
        for(int i = 0; i < dt.Columns.Count; i++) {
            DataGridViewColumn newColumn = new DataGridViewColumn();
            newColumn.Name = dt.Columns[i].ColumnName;
            dataGridView1.Columns.Add(newColumn);
        }   
    
        for (int i = 0; i < dt.Rows.Count; i++) {
            //call ToArray to pass a copy of the data from the datatable
            //(make sure you have 'using System.Linq;' at the top of your file
            dataGridView1.Rows.Add(dt.Rows[i].ItemArray.ToArray());
        }
    }
    

    在 MSDN 的有关 DataGridView.Columns 属性的官方文档中,您可以找到有关以编程方式绑定的更多信息。这是link

    【讨论】:

    • 这个方法我知道,但是我正在做的事情你能帮我吗..如果可能的话
    • 在这种情况下,只需注释行dataGridView1.DataSource = ds.Tables[0],并在for循环中以编程方式完全绑定网格:)
    • 它显示这个错误..索引超出范围。必须是非负数且小于集合的大小。参数名称:行索引...dataGridView1.Rows[i].Cells[j].Value = ds.Tables[0].Rows[i][j].ToString();
    • 怎么办??
    • 这是因为你没有定义网格的列结构。在for 循环之前,您需要添加一个新的for 循环,该循环遍历DataTable 的列,并为数据表中的每一列添加一个新的DataGridViewColumn 对象
    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多