简体   繁体   English

使用dataGridView显示数据库中的数据?

[英]display data from my database using dataGridView?

I want to display data from my database using dataGridView, but I am not getting the desired result. 我想使用dataGridView显示数据库中的数据,但是没有得到想要的结果。 It's showing blank spaces in the table when I run the code. 运行代码时,它在表中显示空白。 Here is the code: 这是代码:

     MySqlCommand cmd = new MySqlCommand(query, ca.getConnection());
     cmd.CommandType = CommandType.Text;                  
     MySqlDataAdapter MyAdapter = new MySqlDataAdapter(cmd);               
     DataSet dSet = new DataSet();                        
     MyAdapter.Fill(dSet);                                       
     dataGridView1.DataSource = dSet.Tables[0];

The question doesn't clearly specifies what exactly the required desired result or the problem is occurring. 问题没有明确说明所需的期望结果或问题到底发生了什么。 But try providing the DataMember property of the DataGridView like in this code below- 但是,尝试像下面的代码一样提供DataGridView的DataMember属性-

string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";

Replace the last line of your code with this code may be this will be helpful once i had a same problem like your one. 用此代码替换代码的最后一行,如果我遇到与您相同的问题,这可能会有所帮助。 But my problem resolved after using this. 但是使用此工具后,我的问题解决了。

dataGridView1.ItemSource = dSet.Tables[0].DefaultView; dataGridView1.ItemSource = dSet.Tables [0] .DefaultView;

Hey listen i am retrieving data from database and i am using below code its working fine..Its SQLSERVER code. 嘿,听着,我正在从数据库中检索数据,我正在使用下面的代码,它的工作正常..它的SQLSERVER代码。 But you could get help for MYSQL from this. 但是您可以从中获得有关MYSQL的帮助。

        SqlDataAdapter da;
        con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\librarydb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        con.Open();
        da = new SqlDataAdapter("select * from student", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM