DataGridView不显示数据

时间:2016-06-11 09:24:08

标签: c# sql .net winforms datagridview

我有以下代码从表中显示DataGridView中的数据。但是DataGridView是空的:

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("sdgds");
            SqlCommand sCommand;
            SqlDataAdapter sAdapter;
            SqlCommandBuilder sBuilder;
            DataSet sDs;
            DataTable sTable;
            string sql = "SELECT * FROM mytable";
            SqlConnection myConnection = new SqlConnection("user id=test;" +
                                       "password=test;server=MOBILE01;" +
                                       "Trusted_Connection=yes;" +
                                       "database=mydatabase; " +
                                       "connection timeout=30");
            myConnection.Open();


            sCommand = new SqlCommand(sql, myConnection);
            sAdapter = new SqlDataAdapter(sCommand);
            sBuilder = new SqlCommandBuilder(sAdapter);
            sDs = new DataSet();

            sAdapter.Fill(sDs);


            sAdapter.Fill(sDs, "mytable");
            dataGridView1.ReadOnly = true;

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            myConnection.Close();
        }
    }
}

3 个答案:

答案 0 :(得分:3)

因为您没有设置DataGridView.DataSource属性:

dataGridView1.DataSource = sDs.Tables["mytable"];

答案 1 :(得分:0)

您尚未将DataSourcegridview

联系起来
dataGridView1.DataSource = sDs.Tabes[0];

答案 2 :(得分:-1)

如果您的目标只是填充DataGridView以显示数据,那么您可能应该摆脱Dataset,DataAdapter填充例程:

private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("sdgds");
            SqlCommand sCommand;
            SqlCommandBuilder sBuilder;
            DataTable sTable;
            string sql = "SELECT * FROM mytable";
            SqlConnection myConnection = new SqlConnection("user id=test;" +
                                       "password=test;server=MOBILE01;" +
                                       "Trusted_Connection=yes;" +
                                       "database=mydatabase; " +
                                       "connection timeout=30");
            myConnection.Open();


            sCommand = new SqlCommand(sql, myConnection);

            /// here is the change - getting data in data reader and filling datatable directly with it.
            var reader = sCommand.ExecuteReader();
            sTable = new DataTable();
            sTable.Load(reader);

            dataGridView1.DataSource = sTable;
            dataGridView1.ReadOnly = true;

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            myConnection.Close();
        }
    }