c#从表中选择一些列 [英] c# select from table some columns
问题描述
我需要从table1的2comboboxes中选择2列,并将这两列中的数据放入listview11中的button1点击事件中
I need to select 2 columns from 2comboboxes from table1 and put the data in these 2 columns in in listview11 in button1 click event
if (cn.State == ConnectionState.Closed) cn.Open();
cm.Connection = cn;
if (comboBox3.Enabled == true)
{
string searchFor2 = comboBox1.Text;
string searchFor3 = comboBox2.Text;
string selectSql = "SELECT " + searchFor2 + ", " + searchFor3 + " FROM itmsparts";
SqlCommand com = new SqlCommand(selectSql, cn);
try
{
using (SqlDataReader read1 = com.ExecuteReader())
{
while (read1.Read())
{
foreach (ListViewItem item in listView1.Items)
{
item.Text = (read1["searchFor2"].ToString());
item.SubItems[1].Text = (read1["searchFor3"].ToString());
}
}
}
}
finally
{
}
}
但没有错误也没有什么是添加到listview1
but no error and no nothing is added to listview1
推荐答案
好吧,我从调试器开始。
在线上放一个断点
Well, I'd start with the debugger.
Put a breakpoint on the line
while (read1.Read())
并查看确切地说是 selectSql
字符串中的内容。
然后,单步编码,看看究竟发生了什么。
我的猜测是,foreach循环没有执行,因为你的listview是空的,或者你得到异常,因为没有返回具有列名searchFor2和searchFor3的结果。这可能会解决这个问题:
and look at exactly what is in the selectSql
string.
Then, single step you code and see exactly what is happening.
My guess is that either the foreach loop doesn't execute because your listview is empty, or you are getting exceptions because there are no results returned that have the column names "searchFor2" and "searchFor3". It's possible that this would fix that:
{
item.Text = (read1[searchFor2].ToString());
item.SubItems[1].Text = (read1[searchFor3].ToString());
但你需要先了解到底发生了什么。
But you need to start by finding out exactly what is happening first.
这篇关于c#从表中选择一些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!