简体   繁体   English

从Access数据库搜索后如何在button_click上填充gridview?

[英]How to populate gridview on button_click after searching from access database?

I am creating a form in c#.net . 我正在c#.net中创建一个表单。 I want to populate the gridview only on button click with entries meeting search criteria. 我只想在按钮单击时使用满足搜索条件的条目来填充gridview

I have tried but on searching ID it works but on searching FirstName it gives error plz check SQL also. 我已经尝试过,但是在搜索ID时它可以工作,但是在搜索FirstName时,它也会给错误plz检查SQL。

Code behind: 后面的代码:

private void button1_Click(object sender, EventArgs e)
 {
            try
            {
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=L:/New project/Project/Project/Data.accdb";

                string sql = "SELECT * FROM AddressBook WHERE FirstName='" + textBox1.Text.ToString();
                OleDbConnection connection = new OleDbConnection(strConn);
                OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
                DataSet ds = new DataSet();
                connection.Open();
                dataadapter.Fill(ds, "AddressBook");
                connection.Close();
                dataGridView1.DataSource = ds;

                dataGridView1.DataMember = "AddressBook";
            }
            catch (System.Exception err)
            {
                this.label27.Visible = true;
                this.label27.Text = err.Message.ToString();
            }
   }

you forgot databind(); 您忘记了databind();

dataGridView1.DataSource = ds;
dataGridView1.DataBind();



"SELECT * FROM AddressBook WHERE FirstName Like '%" + textBox1.Text + "%'";

but remember this sql query is vulnerable to SQL injections so make sure after all works to filter out bad characters 但是请记住,此sql查询容易受到SQL注入的影响,因此请确保毕竟可以过滤掉不良字符

Your error was produced because you did not close your query FirstName='" + textBox1.Text.ToString(); should be FirstName='" + textBox1.Text.ToString() + "'"; 因为未关闭查询FirstName='" + textBox1.Text.ToString();应该是FirstName='" + textBox1.Text.ToString() + "'"; but like that you must type exactly the right name 但是那样你必须输入正确的名字

with using "like" you can get more results 使用“赞”可以得到更多结果

FirstName Like '%" + textBox1.Text.ToString() + "%'";

And ToString() is not needed since the Text Property is already a string 并且ToString()不需要,因为Text属性已经是一个字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM