تابع
.. ADO.net / Connection Mode ""..
.. Select + Where ""..
عرضنا سابقا مثال عن الربط بقواعد البيانات فى حالة الاتصال المباشر بجملة Select.
والان لنبدأ ..أولا : لنصمم معا الشكل التالى :-
بحيث عند اختيار اسم الجهاز يظهر سعره فى Label1 وصورته فى Image1 ..حيث ان اسم الجهاز يتم اختياره من DropDownList1 .
ثالثا : نريد ان نجعل السعر والصورة لجهاز معين يظهر وذلك باستخدام Where بحيث يكون الكود كالتالى
protected void Button1_Click(object sender, EventArgs e) { SqlConnection c = new SqlConnection("Data Source=localhost;database=HCom;Integrated Security=True"); SqlCommand cm = new SqlCommand("Select * From hardware where h_name='" + DropDownList1.SelectedValue + "'", c); c.Open(); SqlDataReader rd = cm.ExecuteReader(); if (rd.Read()) { Label1.Text = rd.GetSqlString(4).Value; Image1.ImageUrl = rd.GetSqlString(3).Value; } rd.Close(); c.Close(); }
نأتى هنا لشرح جملة ال Command ...
"Select * From hardware where h_name='"DropDownList1.SelectedValue + "'"
هنا سوف يأتى ببيانات الجدول hardware ولكن فى حاله ان ال h_name يساوى القيمة المختارة من ال DropDownList1 .
وعند التنفيذ يكون كتالى :
*************************************************************
هناك طريقة اخرى وهى اضافة متغيرات (Parameters ) الى جملة ال Command .ويكون الكود فى هذة الحالة
protected void Button1_Click(object sender, EventArgs e) { SqlConnection c = new SqlConnection("Data Source=localhost;database=HCom;Integrated Security=True"); SqlCommand cm = new SqlCommand("Select * From hardware where h_name=@h_name", c); cm.Parameters.Add("@h_name", DropDownList1.SelectedValue); c.Open(); SqlDataReader rd = cm.ExecuteReader(); if (rd.Read()) { Label1.Text = rd.GetSqlString(4).Value; Image1.ImageUrl = rd.GetSqlString(3).Value; } rd.Close(); c.Close(); }
نأتى هنا لشرح اضافة متغيرات (Parameters ) الى جملة ال Command ...
1- where
h_name=@h_name
حيث ان h_name تساوى اسم المتغير @h_name ويجب وضع @
قبل اسم المتغير
2- cm.Parameters.Add("@h_name",
DropDownList1.SelectedValue);
- Parameters : لتعريف المتغيرات.
- "@h_name" : اسم المتغير.
- DropDownList1.SelectedValue : تحديد قيمة المتغير.
والان جرب
بنفسك وشاهد النتيجة.
*************************************************************
الى
اللقاء فى الدرس القادم
0 comments :
إرسال تعليق