gpt4 book ai didi

c# - 如何在列表框中显示查询结果?

转载 作者:搜寻专家 更新时间:2023-10-30 23:32:29 25 4
gpt4 key购买 nike

我有一个包含实体 AuthorId (int)(AuthorId 是主键)、Name(nvarchar) 和 Nationality(nvarchar ).我还有一个列表框,它显示该数据库中的名称,以及三个文本框,我想在其中显示列表框中所选项目的 ID、姓名和国籍,每个文本框一个。使用我现在所拥有的,我得到以下错误:

Conversion failed when converting the varchar value to data type int.

以下是我如何获取数据并将其显示在列表框中:

public void GetAuthorData()
{
string connectionString = //connection string here
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
var query = "SELECT * FROM Author";
using (SqlCommand cmd = new SqlCommand(query, con))
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Author a = new Author();
a.Id = reader.GetInt32(0);
a.Name = reader.GetString(1);
a.Nationality = reader.GetString(2);

AuthorListBox.Items.Add(a);
}
}
}
}

下面是我在文本框中显示数据的方式:

private void AuthorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DeleteAuthortButton.IsEnabled = true;
SaveChangesButton.IsEnabled = true;

var aa = sender as ListBox;
if (aa.SelectedItem != null)
{
var author = aa.SelectedItem.ToString();
string connectionString = //connection string here
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
var query = "SELECT * FROM Author where Name = '" + author + "'";
using (SqlCommand cmd = new SqlCommand(query, con))
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Author a = new Author();
a.Id = reader.GetInt32(0);
a.Name = reader.GetString(1);
a.Nationality = reader.GetString(2);

IdTextBox.Text = a.Id.ToString();
AuthorNameTextBox.Text = a.Name;
NationalityTextBox.Text = a.Nationality;
}
}
}
}
}

最佳答案

您不需要检索数据库数据。关于作者的所有信息都在列表中。

    private void AuthorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DeleteAuthortButton.IsEnabled = true;
SaveChangesButton.IsEnabled = true;

var aa = sender as ListBox;
if (aa.SelectedItem != null)
{
var author = aa.SelectedItem as Author;

IdTextBox.Text = author.Id.ToString();
AuthorNameTextBox.Text = author.Name;
NationalityTextBox.Text = author.Nationality;
}
}

关于c# - 如何在列表框中显示查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com