Databinding
private DataSet BindGridView(List<int> userids)
{ DataSet ds = new DataSet();
string MysqlStatement = "SELECT OrganisationID, OrganisationName FROM tbl_organisation WHERE OrganisationID=@OrganisationID";
MySqlParameter[] param = new MySqlParameter[1];
foreach (var OrgID in userids)
{
param[0] = new MySqlParameter("@OrganisationID", MySqlDbType.Int32);
param[0].Value = OrgID;
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param);
ds.Merge(ds);
}
Grid_Organisationtable.DataSource = ds;
Grid_Organisationtable.Columns[0].Visible = false;
Grid_Organisationtable.DataBind();
return ds;
}
I pass a list of values to the databinding method. I pass a list with organistionID. how should I do the databinding. It is returning an empty dataset. I am passing the list with values like 60,61,62. The error I am getting is
Unable to cast object of type ‘System.Collections.Generic.List`1[System.Int32]’ to type ‘System.IConvertible’.
You can’t pass in a list of id’s into an SQL query in this way. Your
SELECTstatement as it stands is expecting the parameter passed in to be a single value to be used by theWHEREclause.If you were to stick with this query you will need to loop through your list and pass in each value one at a time and make a seperate database call, for example:
A better alternative would be to use a
WHERE...IN...clause and pass all your id’s in one go as this will only fire one database call and there is not need to pass in parameters:Your third option would to write a stored procedure that accepted an xml string representation of your list and used this to query the database although this is somewhat more complicated. This way allows you to stick to using a parameter.
Note: it is usually very bad practice to not pass in dynamic data as parameters as this can leave you open to Sql injection attacks but in this case as the data is coming from a List parameter passed into your method you can be fairly sure that it isn’t going to mess with your database.