gpt4 book ai didi

c# - 从组合框和文本框中搜索数据。如何在executenotquery()之后将数据加载到datagridview中

转载 作者:行者123 更新时间:2023-11-29 19:13:14 25 4
gpt4 key购买 nike

现在我有一个组合框,我选择“名称”并输入一些文本。我从数据库中查询数据。但现在我不知道如何将数据加载到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");
}

最佳答案

为什么使用 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

关于c# - 从组合框和文本框中搜索数据。如何在executenotquery()之后将数据加载到datagridview中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com