i'm having problems with updating a DataGridView to rows from data from a database. The code I have is as followed:
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();
}
}
And the method is invoked by:
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);
}
}
The Grid its self has 3 Columns named:
ClientName
PostCode
ContactNo
I've tried the following link to assist http://www.rhyous.com/2010/05/28/how-to-query-a-database-in-csharp/ and tried manually modifying to return to the method which would handle the addition of rows. This provided no avail, then I searched some stackoverflow URLs to find the method which uses a while loop on ExecuteQuery.Read()
but this also provided no use
The resolution was quite simple after further research:
I changed the Querying Method to return a DataTable by:
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;
}
and also opened the connection to the Database, and the modified Searchby text box method has been changed to the following:
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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments