将获得数据填充到listbox中的问题
//将获得数据填充到listbox中
string select = "SELECT * FROM Book WHERE 类别= ' " + comSearch.Text + " ' ";
SqlConnection con = new SqlConnection(Form_BookManager.strConnection);
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataSet ds = new DataSet();
da.Fill(ds);
//Book表的字段:BookID(nvchar),类别(nvchar),书名(nvchar),作者(nvchar),……
//BookID是主键
//我想把数据填充到listbox中,在listbox中的每条数据只显示 BookID 书名 作者
//然后当用户点击listbox中的一条数据时在textbox中(FORM中还有一些textbox)显示这条点击的数据的每个列的值(也就是BookID 书名 作者……这些值)
//就是这些功能,我只写了这点代码,下面的代码不会写了,请大哥们给个例子好吗,谢谢了。
[解决办法]
private void MainForm_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
foreach (DataRow dr in ds.Tables[0].Rows)
{
string str = dr[ "BookID "].ToString() + " " + dr[ "书名 "].ToString() + " " + dr[ "作者 "].ToString();
this.listBox1.Items.Add(str);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.textBox1.Text = this.listBox1.Text;
}
[解决办法]
string select = "SELECT * FROM Book WHERE 类别= ' " + comSearch.Text + " ' ";
SqlConnection con = new SqlConnection(Form_BookManager.strConnection);
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataSet ds = new DataSet();
da.Fill(ds);
//数据出来了吧,开始绑定了
this.ListBox1.DataSource = ds.Tables[0].DefaultView;
this.ListBox1.DataBind();
this.ListBox1.DataTextField= "显示的字段 ";
this.ListBox1.DataValueField= "值字段 ";
[解决办法]
我这里有一个参考,你看一下合适不:
private class comItem
{
private string m_BookID;
private string m_类别;
private string m_书名;
private string m_作者;
public comItem(string bookID, string 类别, string 书名, string m_作者)
{
this.m_BookID = bookID;
this.m_类别 = 类别;
this.m_书名 = 书名;
this.m_作者 = 作者;
}
public string BookID
{
get
{
return this.m_BookID;
}
}
public string 类别
{
get
{
return this.m_类别;
}
}
public string 书名
{
get
{
return this.m_书名;
}
}
public string 作者
{
get
{
return this.m_作者;
}
}
public override string ToString()
{
return string.Format( "BookID:{0}书名:{1}作者:{2} ", this.m_BookID, this.m_书名, this.m_作者);
}
}
private void button1_Click(object sender, EventArgs e)
{
string select = "SELECT * FROM Book WHERE 类别= ' " + comSearch.Text + " ' ";
SqlConnection con = new SqlConnection(Form_BookManager.strConnection);
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
this.comBox1.Items.Add(new comItem(dt.Rows[i][ "BookID "].ToString(),dt.Rows[i][ "书名 "].ToString(),dt.Rows[i][ "作者 "].ToString()));
}
}
}
private void comBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comItem item = this.comBox1.SelectedItem as comItem;
if (item != null)
{
this.txtBookID.Text = item.BookID;
this.txt类别.Text = item.类别;
this.txt书名.Text = item.书名;
this.txt作者.Text = item.作者;
}
}