我是Visual Studio的新手。我正在开发一个Visual Studio 2010应用程序,其中我从用户处获取数据,将其存储在数据库表中,并在WPF的数据网格中显示相同的数据。
但是每次数据输入到表中,我都必须关闭应用程序并单击Execute SQL
右键菜单选项来刷新表。
如何在运行时刷新表,以便数据网格显示最新的条目?
这是我的保存按钮点击事件方法。
private void save_button_Click(object sender, RoutedEventArgs e)
{
string eid="", name, dept_txt, city, addr;
name = name_textBox.Text;
addr = addr_textBox.Text;
city = city_textBox.Text;
//Object deptobj = dept_comboBox.SelectedItem;
dept_txt = dept_comboBox.SelectedItem.ToString().Trim();
dept_txt = dept_txt.Substring(dept_txt.LastIndexOf(":") + 1);
eid = id_textBox.Text;
//connection opeining.......
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Users\MYNAME\Downloads\VS projects\employee-v1.2\employee-v1.2\Database1.mdf';Integrated Security=True;User Instance=True";
con.Open();
string query = "insert into employee2(emp_id,emp_name,addr,dept,city) values('" + eid + "','" + name + "','" + addr + "','" + dept_txt + "','" + city + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
我应该怎么做才能在运行时更新数据网格?
您可以尝试mydatagrid.Items.Refresh();
这对我有用:
当你想重新加载数据网格时调用这个函数。
void fill_datagrid()
{
string ConString = "YOUR CONNECTION STRING";
string CmdString ;
SqlConnection con = new SqlConnection(ConString);
CmdString = "SELECT emp_id, emp_name from employee2";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("employee2");
sda.Fill(dt);
employee2DataGrid.ItemsSource = dt.DefaultView;
}