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();
开发者_Python百科 // 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
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:
Using(SqlConnection con=new SqlConnection(connectionString)){}
精彩评论