[英]Fill MYSQL database with datagrid information in C# wpf
Believe me I have googled it. 相信我,我已经用谷歌搜索了。 Its become clear that the C# code used on win-forms doesn't work on C# WPF for semi-obvious reasons.
很明显,出于半明显的原因,用于win窗体的C#代码在C#WPF上不起作用。 What's not obvious though is how to Fill a MYSQL table with modified or completely new data from a data grid.
但是,尚不明显的是如何用数据网格中修改过的数据或全新数据填充MYSQL表。 It works fine the other way around though (filling the datagrid with MYSQL data).
但是,它在其他方面也很好用(用MYSQL数据填充数据网格)。
private void Save_Click(object sender, RoutedEventArgs e)
{
string sqlcon = "datasource = localhost; port = 3306; username = root; password = Avalisque";
string queryadd = "insert into users.login (user_name,pass_word,gender,first_name,second_name,third_name,surname,security_question,answer);";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlCommand cmd = new MySqlCommand(queryadd, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable("login");
da.Fill(ds);
DG.datasource = ds.Tables[0];
da.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(DG being the datagrid). (DG是数据网格)。 and this is the error message:
这是错误消息:
'System.Windows.Controls.DataGrid' does not contain a definition for 'datasource' and no extension method 'datasource' accepting a first argument of type 'System.Windows.Controls.DataGrid' could be found (are you missing a using directive or an assembly reference?) 'System.Windows.Controls.DataGrid'不包含'datasource'的定义,并且找不到扩展方法'datasource'接受类型为'System.Windows.Controls.DataGrid'的第一个参数(是否缺少using指令或装配参考?)
Any form of help much appreciated. 任何形式的帮助,不胜感激。 Kinda desperate here.
金田在这里绝望。 Please and thanks.
请和谢谢。
I think you are looking for DG.ItemsSource = ds.Tables[0].AsEnumerable();
我认为您正在寻找
DG.ItemsSource = ds.Tables[0].AsEnumerable();
You are getting that error because the System.Windows.Controls.DataGrid
doesn't have a property named datasource
. 由于
System.Windows.Controls.DataGrid
没有名为datasource
的属性,因此出现了此错误。
DataTableExtensions.AsEnumerable shows you how to make a DataTable into an Enumarable where T : DataRow DataTableExtensions.AsEnumerable向您展示如何使DataTable成为Enumarable,其中T:DataRow
I think you have a property ItemsSource. 我认为您有一个属性ItemsSource。
Also do not forget that wpf works well with the mvvm pattern. 同样不要忘记,wpf与mvvm模式一起使用效果很好。 In fact your itemsource probably should be an ObservableCollection available in your viewModel.
实际上,您的itemsource可能应该是viewModel中可用的ObservableCollection。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.