[英]refreshing data grid view doesn't work
我想刷新數據網格視圖,但它不起作用我有這樣的 Refresh 方法:
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");
}
}
但數據網格視圖上的數據不會改變。 請幫忙! 但是當我在主窗體上調用此方法時,它可以工作,但我為 main 方法編寫如下:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.