我想刷新数据网格视图,但它不起作用 我有一个像这样的刷新方法:
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的形式调用此函数。 为此,我在提交按钮中这样说,因为我得到相同的文本框值,并在提交后我想在数据库的数据网格视图中显示它们。 我称之为:
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");
}
}
但数据网格视图的数据不会改变。 请帮忙! 但是当我在主窗体上调用此方法时,它可以工作 但我这样写主要方法:
Select()
答案 0 :(得分:1)
试试这个。
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;
}