我正在尝试使用SqlDataReader从数据库中获取数据并将其显示在ListBox控件中。我的数据库有两个表Genre(标识,名称)和Review(标识,标题,GenreId)。我的C#代码如下:
try
{
using (SqlConnection connection =
new SqlConnection(@"Server=" + txtServerName.Text + ";Database=" + txtDatabase.Text + "; Integrated Security=SSPI"))
using (SqlCommand command =
new SqlCommand("Select Genre.Name, Review.Title " +
"From Genre Inner Join Review " +
"On Genre.Id = Review.GenreId;", connection))
{
connection.Open();
MessageBox.Show("Connected successful!");
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string sFormat = String.Format("Name: {0} Title: {1}", reader.GetString(0), reader.GetString(1));
// adding data to ListBox
lst.Items.Add(sFormat);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
在上面运行代码时,我只有“名称”列,而“标题”列没有出现。但是,如果我如下更改sFormat变量:
string sFormat = String.Format("Title: {0} Name: {1}", reader.GetString(1), reader.GetString(0));
,我同时看到了“名称”列和“标题”列。
我不知道为什么?请帮帮我!
答案 0 :(得分:0)
请检查是否可行
string sFormat = String.Format("Title: {0} Name: {1}", reader["Name"].ToString(), reader["Title"].ToString());