C#遍历记录
问题描述:
现在,我使用MS SQL 2005在C#中建立了连接,当我单击按钮时,我希望显示第一行,并在第二次单击时在文本框中显示下一条记录。C#遍历记录
它会在循环中的东西,但如何?
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();
}
}
}
没有错误可言我希望按钮的只是功能当过我点击我的文本框
答
提供下一个记录,不要忘记投票了。 正确的方法是基于数据库中的表是固定的。 ,以避免每次点击数据库时都要使用SqlDataAdapter并获取所有表,并在点击表的时候运行。 (不要忘记保持一个全局变量的当前行指望任何一次性类 一个更重要的东西─使用Using
,确保处置和追赶expections 样本:。
Using(SqlConnection con=new SqlConnection(connectionString)){}
+0
可以告诉我更多详细信息吗?一些源代码? – salman 2010-11-09 14:11:48
你能分享更多的代码?如果不查看代码,很难说出什么问题......您是否尝试过测试数据读取器(例如控制台应用程序)以确保它返回您想要的内容并且该错误不在数据检索逻辑中? – zam6ak 2010-11-09 13:44:50
网页或桌面? – 2010-11-09 13:45:59
其桌面应用程序 – salman 2010-11-09 13:58:29