现在我有一个组合框,我选择“名称”并输入一些文字。我有来自我的数据库的查询数据。但现在我不知道如何将数据加载到datagridview。 这是我的代码按钮搜索:
private void btnSearch_Click(object sender, EventArgs e)
{
String strSearch = txtSearch.Text.Trim();
String Selected = cbSearch.GetItemText(cbSearch.SelectedItem);
switch (Selected)
{
case "All Search":
LoadData();
break;
case "Name":
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
MySqlCommand cmd = new MySqlCommand("Select * FROM sinhvien where name LIKE @name");
cmd.Connection = conn;
cmd.Connection.Open();
cmd.Parameters.Add(new MySqlParameter("@name", "%" + txtSearch.Text + "%"));
cmd.ExecuteNonQuery();***//I dont't know what to do after query here***
MessageBox.Show("Delete this row successfully!\n",
"Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (MySqlException)
{
MessageBox.Show("Error load data from database!","Notification", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
break;
break;
}
}
然后如何将数据从数据库加载到datagridview:
private void LoadData()
{
try
{
conn = new MySqlConnection(connString);
if (conn.State == ConnectionState.Open)
conn.Close();
daSinhVien = new MySqlDataAdapter("SELECT * FROM sinhvien", conn);
dtSinhVien = new DataTable();
dtSinhVien.Clear();
daSinhVien.Fill(dtSinhVien);
dgvSinhVien.DataSource = dtSinhVien;
}
catch (MySqlException)
{
MessageBox.Show("Can't not load data from sinhvien!!","Notification",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
cbSearch.Items.Add("All Search");
cbSearch.Items.Add("Name");
cbSearch.Items.Add("Age");
cbSearch.Items.Add("Class");
cbSearch.Items.Add("Address");
}
答案 0 :(得分:0)
为什么使用cmd.ExecuteNonQuery();?
用于执行您不希望返回数据的语句 - 就像调整某些记录的命令一样。
相反,你可能正在寻找类似的东西:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
...这是在MSDN页面之外:https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx