我想刷新数据 GridView ,但它不起作用 我有一个像这样的刷新方法:
public void Select()
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
string cs = "server=(local);database=DB_Taxi;trusted_connection=yes;";
con.ConnectionString = cs;
con.Open();
cmd.Connection = con;
da.SelectCommand = cmd;
cmd.CommandText = "SELECT * FROM Tbl_Driver";
da.Fill(dt);
con.Close();
grid.DataSource = dt;
}
它在主窗体上。 我想以另一种名为 Add_Driver 的形式调用此函数。 为此,我在提交按钮中这样告诉它,因为我得到了相同的文本框值,并且在提交它们之后我想在数据库的数据 GridView 中显示它们。 我这样调用它:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtID.Text != "" || txtName.Text != "" || txtLastName.Text != "" || txtMobile.Text != "" ||
txtPhone.Text != "" || txtCar.Text != "" || txtGender.Text != "" || txtAddress.Text != "")
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string cs = "server=(local);database=DB_Taxi;trusted_connection=yes;";
con.ConnectionString = cs;
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Tbl_Driver(DriverID,DName,DLastName,DMobile,DAddress,DCar,DGender,DPhone) VALUES(@ID,@Name,@LastName,@Mobile,@Address,@Car,@Gender,@Phone)";
cmd.Parameters.AddWithValue("@ID", txtID.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Car", txtCar.Text);
cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
cmd.ExecuteNonQuery();
con.Close();
Empty();
////////////////////
Main m = new Main();
m.Select();
////////////////////
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Plese complete the form");
}
}
但数据 GridView 中的数据不会改变。 请帮忙! 但是当我在主窗体上调用这个方法时它起作用了 但我这样写主要方法:
Select()
最佳答案
试试这个。
public void Select() {
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
string cs = "server=(local);database=DB_Taxi;trusted_connection=yes;";
con.ConnectionString = cs;
con.Open();
cmd.Connection = con;
da.SelectCommand = cmd;
cmd.CommandText = "SELECT * FROM Tbl_Driver";
da.Fill(dt);
con.Close();
//clearing the datasource
grid.DataSource = null;
//set the datasource
grid.DataSource = dt;
}
关于c# - 刷新数据 GridView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867422/