DataGridView 中怎么读取SQLserver数据库的数据,进行显行
好心人贴下代码哦! 谢谢了.

解决方案 »

  1.   

    不是DataGridView 中读取数据显示,而是选读出数据用DataGridView来显示.参考下如下的MSDN示例:
    下面的代码示例演示如何初始化简单数据绑定 DataGridView。它还演示如何设置 DataSource 属性。若要运行此示例,请执行以下操作:将以下代码粘贴到一个窗体中,该窗体包含名为 dataGridView1 的 DataGridView;将代码中指定的 connectionString 变量的值替换为对运行该示例的系统有效的字符串;在窗体的构造函数或 Load 事件处理程序中调用 InitializeDataGridView 方法。C#  复制代码 
    private void InitializeDataGridView()
    {
        try
        {
            // Set up the DataGridView.
            dataGridView1.Dock = DockStyle.Fill;        // Automatically generate the DataGridView columns.
            dataGridView1.AutoGenerateColumns = true;        // Set up the data source.
            bindingSource1.DataSource = GetData("Select * From Products");
            dataGridView1.DataSource = bindingSource1;        // Automatically resize the visible rows.
            dataGridView1.AutoSizeRowsMode =
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;        // Set the DataGridView control's border.
            dataGridView1.BorderStyle = BorderStyle.Fixed3D;        // Put the cells in edit mode when user enters them.
            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this sample replace connection.ConnectionString" +
                " with a valid connection string to a Northwind" +
                " database accessible to your system.", "ERROR",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            System.Threading.Thread.CurrentThread.Abort();
        }
    }private static DataTable GetData(string sqlCommand)
    {
        string connectionString = "Integrated Security=SSPI;" +
            "Persist Security Info=False;" +
            "Initial Catalog=Northwind;Data Source=localhost";    SqlConnection northwindConnection = new SqlConnection(connectionString);    SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;    DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;
        adapter.Fill(table);    return table;

      

  2.   

    dataGridView1.DataSource = GetData("Select * From Products");
    //关键是这句, dataGridView1把一个TableTable作为显示用的数据源