读书人

VS2010用C#访问SQL数据库念实现用li

发布时间: 2013-09-11 16:26:28 作者: rapoo

VS2010用C#访问SQL数据库,想实现用listbox1控件显示表1的某列,listbox2控件显示表2的某列,代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

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

private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“siplace_kanbanDataSet1.kanbanTable”中。您可以根据需要移动或删除它。
this.kanbanTableTableAdapter.Fill(this.siplace_kanbanDataSet1.kanbanTable);
BindListBox1();
//BindListBox2();
}

//设定ListBox控件显示内容
public void BindListBox1()
{
string sql1 = "select lId,dtTime from BOARD";
string sql2 = "select dtTime from CompBlock";
listBox1.DataSource = GetData1(sql1).Tables[0];
listBox1.DisplayMember = "lId";
listBox2.DataSource = GetData2(sql2).Tables[1];
listBox2.DisplayMember = "dtTime";
}

/*public void BindListBox2()
{
string sql2 = "select dtTime from CompBlock";


listBox2.DataSource = GetData2(sql2);
listBox2.DisplayMember = "dtTime";
}*/

private DataSet GetData1(string sql)
{
DataSet table1 = new DataSet();
String connectionString =
"Data Source=SZNC4924;" + "Initial Catalog=OIS1;User ID=sa;Password=Siplace.1";
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter1 = new SqlDataAdapter(sql,conn);
dataAdapter1.Fill(table1);
return table1;
}

private DataSet GetData2(string sql)
{
DataSet table2 = new DataSet();
String connectionString =
"Data Source=SZNC4924;" + "Initial Catalog=OIS1;User ID=sa;Password=Siplace.1";
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter2 = new SqlDataAdapter(sql, conn);
dataAdapter2.Fill(table2);
return table2;
}
}

}
结果listbox1有显示结果,可是listbox2没有 这是什么原因 怎么解决?


[解决办法]
listBox2.DataSource = GetData2(sql2).Tables[0];

读书人网 >C#

热点推荐