C# 遍历记录
我现在用 C# 与 MS SQL 2005 建立连接,当我单击按钮时,我希望显示第一行,当第二次单击时,在文本框中显示下一条记录。
这将是循环内的东西,但如何?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=SERVER1\\SQLEXPRESS;Initial Catalog=try;Integrated Security=True;Pooling=False");
SqlDataReader rdr = null;
try
{
conn.Open();
// 3. Pass the connection to a command object
MessageBox.Show("connection opened");
SqlCommand cmd = new SqlCommand("select * from trytb", conn);
// 4. Use the connection
// get query results
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//rdr.Read();
MessageBox.Show(rdr[0].ToString() + rdr[1].ToString());
//textBox1.Text = rdr[0].ToString();
// textBox2.Text = rdr[1].ToString();
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally
{
// close the reader
if (rdr != null)
{
MessageBox.Show("reader closing");
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
MessageBox.Show("connection closing");
conn.Close();
}
}
}
根本没有错误,我只想要按钮的功能,每当我单击时,我都会在文本字段中提供下一条记录
I made my connection in C# with MS SQL 2005 now when I click a button I want the first row to be displayed and when clicked a second time, show the next record in the a text box.
it would be something in side the loop but how??
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=SERVER1\\SQLEXPRESS;Initial Catalog=try;Integrated Security=True;Pooling=False");
SqlDataReader rdr = null;
try
{
conn.Open();
// 3. Pass the connection to a command object
MessageBox.Show("connection opened");
SqlCommand cmd = new SqlCommand("select * from trytb", conn);
// 4. Use the connection
// get query results
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//rdr.Read();
MessageBox.Show(rdr[0].ToString() + rdr[1].ToString());
//textBox1.Text = rdr[0].ToString();
// textBox2.Text = rdr[1].ToString();
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally
{
// close the reader
if (rdr != null)
{
MessageBox.Show("reader closing");
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
MessageBox.Show("connection closing");
conn.Close();
}
}
}
there is no error at all i want just the functionality of the button when ever i click i provide next record in textfield
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
别忘了投票。
正确的方法是基于数据库中的表是固定的这一事实。
为了避免每次单击时查询数据库,最好使用 SqlDataAdapter 并获取所有表,而不是每次单击时在表上运行。 (不要忘记保留一个全局变量来计算当前行。
更重要的一件事 - 在任何一次性类上使用
Using
来确保处理和捕获期望。样本:
Don't forget to vote up.
the correct way to do this is based on the fact that the table in the DB is fixed.
to avoid from quering the DB each time you click it's better to use SqlDataAdapter and take all the table and than run on the table eack time you click. (don't forget to keep a global variable for counting the current row.
one more important thing- use
Using
on ANY disposable class to ensure disposing and catching expections.sample: