正如标题所述,我的代码片段来自我教授提供的一个例子。
我的输出是:
MagazineID Title Publisher Price SubscriptionRate
1 People Times Inc. 4.95 19.95
2 Car and Driver Hachetter Inc. 3.95 19.99
代码:
private void btnShowMags_Click(object sender, EventArgs e)
{
// Creating new instance of the DisplayMags form.
DisplayMags displayMags = new DisplayMags();
// find the path where the executable resides
string dbPath = Application.StartupPath;
// Providing a path to the MS Access file.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
+ dbPath + @"\..\..\..\..\Magazines.mdb; User Id=admin; Password=";
// Creating a new connection and assigning it to a variable.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
// Creating a new instance for a command which we will use later.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// declare and instantiate the command
OleDbCommand cmdMagazines = new OleDbCommand();
cmdMagazines.CommandText = "select * from magazine";
cmdMagazines.Connection = conn;
OleDbDataReader drMagazines;
try
{
// open the connection
conn.Open();
// retrieve data from the data source to the data reader
drMagazines = cmdMagazines.ExecuteReader();
if (drMagazines.HasRows)
{
// populate the column headings
for (int i = 0; i < drMagazines.FieldCount; i++)
displayMags.txtDisplayMags.Text += drMagazines.GetName(i) + " ";
displayMags.txtDisplayMags.Text += "\r\n";
// populate the data by row
while (drMagazines.Read())
{
for (int i = 0; i < drMagazines.FieldCount; i++)
displayMags.txtDisplayMags.Text += drMagazines.GetValue(i) + " ";
displayMags.txtDisplayMags.Text += "\r\n";
}
}
}
catch (Exception ex)
{
// Displaying any errors that might have occured.
MessageBox.Show("Error opening the connection: " + ex.Message + "\r\n");
}
finally
{
// Closing connection after task was completed.
conn.Close();
}
// Displaying DisplayMags form, assuring that earlier form
// will not be accessible. Show() let us access all forms.
displayMags.ShowDialog();
}
而且,我试图让它看起来像这样:
EDIT。这项工作,但这是否代表了正确的编程实践?
if (drMagazines.HasRows)
{
while (drMagazines.Read())
{
displayMags.txtDisplayMags.Text += "=== Magazine " +
drMagazines.GetValue(0) + " ===" + Environment.NewLine +
drMagazines.GetValue(1) + Environment.NewLine +
drMagazines.GetValue(2) + Environment.NewLine +
drMagazines.GetValue(3) + Environment.NewLine +
drMagazines.GetValue(4) + Environment.NewLine +
Environment.NewLine;
}
}
答案 0 :(得分:3)
我没有给你完整的答案,因为那会破坏作业的目的,你就不会学到任何东西。但是,我可以为您提供解决问题的方法。
您的输出从以if (drMagazines.HasRows)
开头的块开始。该块中的代码是您进行更改所需的位置。
您需要对其进行更改,以便打印包含杂志编号,行结尾(Environment.NewLine
)的分隔符,而不是打印出列标题然后打印每行的内容,然后分隔行有标题,然后有内容。
您现在的代码中包含必要的信息 - 您在populate the column headings
然后populate the data by row
处有评论。更改为populate a single heading
然后populate the row content for that heading
。建议将其从两个循环更改为一个 - 读取列标题,然后读取它包含的行内容。您可以在该循环期间为每个项目添加任何其他内容或格式。