本人通过dgv的属性datasource绑定了数据源,求大牛帮本人看下是哪里出问题啦
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private delegate void myDelegate(DataTable dt);//定义委托
DataTable DT = new DataTable();
private SqlDataAdapter da = null;
private BindingSource bindingSource1 = null;
private void MainForm_Load(object sender, EventArgs e)
{
//开线程
myThread = new Thread(startThread);
myThread.IsBackground = true;
myThread.Start();
}
private void startThread()
{
DataTable dt1 = GetDataTable();
Grid(dt1);
while (true)
{
if (Createtb.isInsert)//当有数据插入时进入
{
DataTable dt = GetDataTable();
Grid(dt);
Createtb.isInsert = false;
}
Thread.Sleep(3000);
}
}
private void Grid(DataTable dt)
{
if (this.InvokeRequired)//等待异步
{
this.Invoke(new myDelegate(Grid), new object[] { dt });
}
else
{
try
{
this.Dgv_SQLData.DataSource = null;
this.Dgv_SQLData.DataSource = dt;
bindingSource1 = new BindingSource();
bindingSource1.DataSource = dt;
dt = null;
}
catch (Exception)
{
throw (new System.Exception());
}
}
}
private DataTable GetDataTable()
{
string strConn = “”;
strConn = GetDBConnStr();
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = strConn;
da = new SqlDataAdapter();
string tmp = “”;
string strTBName = “”;
strTBName = Global.g_strTBName;
tmp = string.Format(“select * from {0}”, strTBName);
SqlCommand cmd1 = new SqlCommand(tmp, myConn);//sql语句
da.SelectCommand = cmd1;//设置为已实例化SqlDataAdapter的查询命令
da.Fill(DT);//把数据填充到dataset
return DT;
}
/// <summary>
/// 连接字符串
/// </summary>
/// <returns></returns>
private string GetDBConnStr()
{
string strTemp =””;
string strDBName = Global.g_strDBName;
strTemp = string.Format((“Data Source=TX-PC\SQLEXPRESS;Initial Catalog={0};Integrated Security=True”), strDBName);
return strTemp;
}
//button按键
private void button1_Click(object sender, EventArgs e)
{
string strDBName = “”;
string strTBName = “”;
strDBName = Global.g_strDBName;
strTBName = Global.g_strTBName;
Createtb.InsertTable(strTBName, strDBName);
//当点击测量时,开启线程,从OPC服务器接收到数据的时候,就向数据库插入数据,并且更新到datagridview
}
/// <summary>
/// 向数据库写内容
/// </summary>
privat void InsertTable(string strTBName, string strDBName)
{
//判断能否连接,向表里写入数据
string strConn = “”;
strConn = GetDBConnStr();
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = strConn;
if (myConn.State == ConnectionState.Open)
myConn.Close();
string ConnectionString = string.Format((“Data Source=TX-PC\SQLEXPRESS;Initial Catalog={0};Integrated Security=True”), strDBName);
myConn.ConnectionString = ConnectionString;
if (myConn.State != ConnectionState.Open)
myConn.Open();
InsertSql = string.Format(“INSERT INTO {0} ({1}) VALUES ({2})”, strTBName, “宽度”, 66);
cmd = new SqlCommand(InsertSql, myConn);
cmd.ExecuteNonQuery();
isInsert = true;
}
}
30
你断点在绑定前看下datatable里数据能否正确
10
重新绑定,原来的datatable舍弃。