To display the values from the DataReader
into the text boxes, you need to assign the values from the reader to the text boxes inside the while
loop. However, you can’t directly assign values to reader["Column1"]
and reader["Column2"]
because they are read-only. Instead, you need to assign the values to the text boxes directly. Here’s how you can modify your code:
csharpprivate void button2_Click(object sender, EventArgs e)
{
SqlCommand rcmd = new SqlCommand("SELECT ID, Column1, Column2 FROM [TEST].[dbo].[Table_1] where ID=@ID", connection);
rcmd.Parameters.AddWithValue("@ID", textBox3.Text);
connection.Open();
SqlDataReader reader = rcmd.ExecuteReader();
while (reader.Read())
{
textBox4.Text = reader["Column1"].ToString();
textBox5.Text = reader["Column2"].ToString();
}
connection.Close();
}
This code will populate textBox4
with the value from “Column1” and textBox5
with the value from “Column2” for the specified ID.
المزيد من المعلومات
للتأكد من أن القراءة تتم بشكل صحيح، يمكنك إضافة بعض التحققات. قبل تعيين القيم إلى الـ textBoxes، يمكنك التحقق مما إذا كان هناك صفوف متاحة في النتيجة باستخدام خاصية HasRows
من DataReader
. هذا يساعد في تجنب الأخطاء إذا كانت النتيجة فارغة. إليك كيف يمكنك تعديل الكود ليتضمن هذا التحقق:
csharpprivate void button2_Click(object sender, EventArgs e)
{
SqlCommand rcmd = new SqlCommand("SELECT ID, Column1, Column2 FROM [TEST].[dbo].[Table_1] where ID=@ID", connection);
rcmd.Parameters.AddWithValue("@ID", textBox3.Text);
connection.Open();
SqlDataReader reader = rcmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
textBox4.Text = reader["Column1"].ToString();
textBox5.Text = reader["Column2"].ToString();
}
}
else
{
MessageBox.Show("No rows found.");
}
connection.Close();
}
هذا التعديل يتيح لك عرض رسالة تنبيه إذا لم تتم العثور على أي صفوف تطابق الشرط المحدد.