我正在为我的学校做一个项目,我必须在那里制作一个C#Windows Forms应用程序,让我可以与我的PostgreSQL数据库进行交互。我已经创建了一个列表框,它应该从我的数据库中获取表的名称,当我选择这些名称时,该表中的数据将显示在表单中的datagridview对象中。但问题是,我的所有列表框值都是System.Data.DataRowView,而datagridview只显示列表中第一个表的值。
代码:
DataTable tabulusaraksts = new DataTable();
DataTable tabula = new DataTable();
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlDataAdapter adapter2 = new NpgsqlDataAdapter();
string tab;
public datubaze()
{
InitializeComponent();
string connectionstring = "Server=localhost;Port=5432;UserId=postgres;Password=students;Database=retrospeles;";
//string connectionstring = String.Format("Server={0};Port={1};" +
// "User Id={2};Password={3};Database={4};",
// serveris.ToString(), port.ToString(), user.ToString(),
// password.ToString(), database.ToString());
NpgsqlConnection ncon = new NpgsqlConnection(connectionstring);
NpgsqlCommand listfill = new NpgsqlCommand("select table_name from INFORMATION_SCHEMA.tables WHERE table_schema = ANY (current_schemas(false));", ncon);
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.DataSource = tabulusaraksts;
listBox1.DisplayMember = "table_name";
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
tab = listBox1.GetItemText(listBox1.SelectedItem);
adapter2.Fill(tabula);
dataGridView1.DataSource = tabula;
}
答案 0 :(得分:0)
该代码应该有效。我尝试了一些测试数据,ListBox
填充了正确的值。
当然,请尝试将ValueMember
设置为
listBox1.DisplayMember = "table_name";
我认为最好的方法是使用循环或Linq列表向DataTable
添加ListBox
行。填写tabulusaraksts
后,DataRows
进行迭代并将其作为项目添加到ListBox
,而不设置DataSource
这样的内容(Linq):
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.AddRange(tabulusaraksts.AsEnumerable().Select(row => row[0].ToString()).ToArray());
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
或使用foreach
循环
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.Clear();
foreach (DataRow row in tabulusaraksts.Rows)
{
listBox1.Items.add(tabulusaraksts[0].ToString());
}
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;