如何为Sql C#检查一行# [英] How Do I Check A Row For Sql C#

查看:65
本文介绍了如何为Sql C#检查一行#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button2_Click(object sender, EventArgs e)
        { 
           if (textBox1.Text.Trim().Length == 0)
                MessageBox.Show("Please fill this area first");
            
            else
            {
                SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AG_DB;Integrated Security=True");
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Musteri where ID = '" + textBox1.Text + "'", con);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                textBox1.Text = dt.Rows[0][0].ToString();
                textBox2.Text = dt.Rows[0][1].ToString();
                textBox3.Text = dt.Rows[0][2].ToString();
                textBox4.Text = dt.Rows[0][3].ToString();
                textBox5.Text = dt.Rows[0][4].ToString();
                textBox6.Text = dt.Rows[0][5].ToString();
                textBox7.Text = dt.Rows[0][6].ToString();
                textBox8.Text = dt.Rows[0][7].ToString();
            }
        }



这是我的代码,它从sqlserver读取数据并使用textbox1填充所有文本框。我需要一个异常,当我在我的sql ID列上不存在的textbox1上写东西时会发出警告。我该怎么办?


this is my code that reads data from sqlserver and fills all textboxes using textbox1. I need an exception that warns me when i write something on textbox1 that doesn't exist on my sql ID Column. How can i do that?

推荐答案

确认数据表中有数据行;

Confirm that you have a data row in the data table;
if(dt.Rows.Count > 0)
{
textBox1.Text = dt.Rows[0][0].ToString();
...
}
else


为什么TextBox1的?请改用下拉列表。使用数据库表中的id填充该下拉列表。例如:

从数据库填充下拉列表 - ASP .NET [ ^ ]

通过这种方式,您无需检查用户对数据库的输入。

了解更多: DropDownList类 [ ^ ]
Why textbox1? Use a dropdownlist instead. Populate that dropdownlist with the ids from the database table. e.g.:
Populate Dropdownlist from Database - ASP.NET[^]
In this way, you do not need to check the user's input against the database.
Read more: DropDownList Class[^]


0)使用语句使用

1)使用参数化命令。

2)不要使用DataAdapter或DataTable。

3)使用DataReader只是尝试从中读取,它将有数据或不会。
0) Use using statement.
1) Use a parameterized command.
2) Don't use a DataAdapter or DataTable.
3) Use a DataReader and just try reading from it, it will have data or it won't.


这篇关于如何为Sql C#检查一行#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆