无法从DB Query更新DataGridView行

时间:2014-08-03 02:14:56

标签: c# sql datagridview

我在将DataGridView更新为数据库中的数据行时遇到问题。我的代码如下:

    public Array ClientSearch(string Argument, string SearchType)
    {
        Connection.Open();
        string QueryStr = "SELECT ClientName,PostCode,ContactNo FROM ClientSearch WHERE "+SearchType+" LIKE %"+Argument+"%";



        SqlCommand Query = new SqlCommand(QueryStr, Connection);

        SqlDataReader ExecuteQuery = Query.ExecuteReader();

        DataTable ResultSet = new DataTable();

        ResultSet.Load(ExecuteQuery);
        Connection.Close();
        if (ResultSet.Rows.Count.Equals(0))
        {
            return null;
        }
        else
        {

            // Single-dimensional array (strings).
            System.Collections.ArrayList Results = new System.Collections.ArrayList();
            while (ExecuteQuery.Read())
            {
                Results.Add(ExecuteQuery.GetString(0));
            }

            return Results.ToArray();

        }
    }

该方法由以下方式调用:

    private void SearchBy_TextChanged(object sender, EventArgs e)
    {
        SQLCmdSet Database = new SQLCmdSet();
        string Param = "";
        if (this.ByName.Checked.Equals(true))
        {
            Param = "ClientName";
        }
        if (this.ByPostCode.Checked.Equals(true))
        {
            Param = "PostCode";
        }
        Array Array = Database.ClientSearch(this.SearchBy.Text, Param);

        foreach (string Element in Array)
        {
            this.ClientInfor.Rows.Add(Element);
        }
    }

网格本身有3个名为:

的列
  

CLIENTNAME

     

邮编

     

ContactNo

我已尝试使用以下链接来协助http://www.rhyous.com/2010/05/28/how-to-query-a-database-in-csharp/并尝试手动修改以返回处理添加行的方法。这没有用,然后我搜索了一些stackoverflow URL以找到在ExecuteQuery.Read()上使用while循环的方法,但这也没有用#/ p>

1 个答案:

答案 0 :(得分:0)

经过进一步研究后,决议非常简单:

我更改了查询方法以通过以下方式返回DataTable:

 public DataTable ClientSearch(string Argument, string SearchType)
        {
            Connection.Open();
            string QueryStr = "SELECT ClientName,PostCode,ContactNo FROM Clients WHERE " + SearchType + " LIKE '%" + Argument + "%'";
            DataTable DataT = new DataTable();
            SqlDataAdapter SQLDA = new SqlDataAdapter(QueryStr, Connection);
            SQLDA.Fill(DataT);
            return DataT;

        }

并且还打开了与数据库的连接,修改后的Searchby文本框方法已更改为以下内容:

    private void SearchBy_TextChanged(object sender, EventArgs e)
    {
        SQLCmdSet Database = new SQLCmdSet();
        string Param = "";
        if (this.ByName.Checked)
        {
            Param = "ClientName";
        }
        if (this.ByPostCode.Checked)
        {
            Param = "PostCode";
        }

        this.ClientInfor.DataSource = Database.ClientSearch(this.SearchBy.Text,Param);

    }