将数据从表格复制到C#中的网格视图 [英] copy data from a tabel to a gride view in c#

查看:71
本文介绍了将数据从表格复制到C#中的网格视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接到db并从表中读取数据,然后在网格视图中显示它,但此Tabel标头添加到我的gridview标头后,但我想将数据放入我的网格视图中 我的代码是:

i want to connect to db and read data from a table then show it in grid view but after do this tabel header add to my gridview header but i want to data be in my gride view
my code is:

DataTable k = new System.Data.DataTable();
           try
           {

               string str = "Data Source=C:\\Documents and Settings\\almas\\Desktop\\BazarKhodro\\khodro.sdf";
               Qconnection.ConnectionString = str;
               Qcommand.Connection = Qconnection;


               string commandText = "select name,lname,phone,mobile,address from moshtari where name=@name and lname=@lname";
               Qcommand.Parameters.AddWithValue("@name", textBox3.Text);
               Qcommand.Parameters.AddWithValue("@lname", textBox4.Text);
               Qcommand.CommandText = commandText;
               Qcommand.CommandType = CommandType.Text;
               SqlCeDataAdapter a = new SqlCeDataAdapter();
               a.SelectCommand = Qcommand;
               a.Fill(k);
               Qconnection.Open();
               Qconnection.Close();
               dataGridView1.DataSource = k;

           }
           catch (Exception ex)
           {

               throw new Exception(ex.Message);

           }

推荐答案

尝试以下操作:

Try this:

try
{
     DataTable k = new System.Data.DataTable();
    string str = "Data Source=C:\\Documents and Settings\\almas\\Desktop\\BazarKhodro\\khodro.sdf";
    Qconnection.ConnectionString = str;
    Qcommand.Connection = Qconnection;


    string commandText = "select name,lname,phone,mobile,address from moshtari where name=@name and lname=@lname";
    Qcommand.Parameters.AddWithValue("@name", textBox3.Text);
    Qcommand.Parameters.AddWithValue("@lname", textBox4.Text);
    Qcommand.CommandText = commandText;
    Qcommand.CommandType = CommandType.Text;
    SqlCeDataAdapter a = new SqlCeDataAdapter();

     a.SelectCommand = Qcommand;


      a.Fill(k);
      BindingSource bSource = new BindingSource();

      bSource.DataSource = k;

      dataGridView1.DataSource = bSource;

    Qconnection.Close();


}
catch (Exception ex)
{

    throw new Exception(ex.Message);

}


如果您要使用自己的名称作为列标题,而不是使用数据库中定义的字段名称,则可以执行以下操作:

If you''re saying that you want to use your own names for the column headers istead of the field names defined in the database, you can do this:

...
Qconnection.Open();
Qconnection.Close();
dataGridView1.DataSource = k;

dataGridView1.Columns[0].Name = "My Name For Column 0";
dataGridView1.Columns[1].Name = "My Name For Column 1";


,您也可以在源代码中更改HeaderText =" Column Name.
You can change the HeaderText = "Column Name" in source code also.


这篇关于将数据从表格复制到C#中的网格视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆