日期:2014-05-17  浏览次数:21061 次

DataGridView不显示数据
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication13
{
  public partial class Form1 : Form
  {
  SqlConnection conn = new SqlConnection("server=.;Uid=sa;Pwd=;database=test");
  public Form1()
  {
  InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
  conn.Open();
  SqlDataAdapter da = new SqlDataAdapter("select f_NO,f1,f2,f3 from test", conn);
  DataSet ds = new DataSet();
  da.Fill(ds, "t1");
  bindingSource1.DataSource = ds.Tables["t1"];
  //dataGridView1.DataSource = ds.Tables["t1"].DefaultView;
  //bindingSource1.DataSource = ds.Tables["t1"].DefaultView;
  //dataGridView1.DataMember = "f1";
  //dataGridView1.DataSource = bindingSource1;
  conn.Close();
  }
  }
}

//在窗体上已经加了DataGridView 并为它绑定了bindingSource1

------解决方案--------------------
你把注释//dataGridView1.DataSource = bindingSource1; 取消掉,数据是不是出了?

在设计器里面设置的绑定不行,具体原因我也没研究清楚,希望高手出来指点
------解决方案--------------------
bindingSource1.DataBind()
------解决方案--------------------
把bindingSource1.DataSource = ds.Tables["t1"];换成 dataGridView1.DataSource = ds.Tables["t1"]; 其余的删除。其实代码写到这里是bindingSource1也可以不用的