我有datagridview
与datatable
绑定并使用DataPropertyName
datagridview
仅显示4列database
。
这是我将database
绑定到datagridview
:
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings
["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from SelectedFeeds", Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
frm.RationFeedsdataGridView.AutoGenerateColumns = false;
frm.RationFeedsdataGridView.Columns[1].Name = "نام خوراک";
frm.RationFeedsdataGridView.Columns[1].HeaderText = "نام خوراک";
frm.RationFeedsdataGridView.Columns[1].DataPropertyName = "Feed Name / Description";
frm.RationFeedsdataGridView.Columns[2].Name = "مقدار (کیلوگرم)";
frm.RationFeedsdataGridView.Columns[2].HeaderText = "مقدار (کیلوگرم)";
frm.RationFeedsdataGridView.Columns[2].DataPropertyName = "Quantity";
frm.RationFeedsdataGridView.Columns[3].Name = "درصد (خوراک)";
frm.RationFeedsdataGridView.Columns[3].HeaderText = "درصد (خوراک)";
frm.RationFeedsdataGridView.Columns[3].DataPropertyName = "Percent";
frm.RationFeedsdataGridView.DataSource = DTable;
到目前为止没有错,
现在我希望当用户更改Columns[2]
的值时,它的值会自动插入(并在更新之后)到database
我尝试自己使用此代码,但似乎是&#39 ;错了,代码是:
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings
["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
double Quantity = Convert.ToDouble(frm.RationFeedsdataGridView.CurrentCell.Value);
string FeedName = frm.RationFeedsdataGridView.CurrentRow.Cells[1].Value.ToString();
Connection.Open();
Cmd.CommandText="Update SelectedFeeds set Quantity=" +Quantity 'Where Feed Name / Description'= FeedName;
Cmd.ExecuteNonQuery();
Connection.Close();
第一个问题是我的CommandText错了,我不知道如何解决它。 我该怎么办?
答案 0 :(得分:4)
public static void UpdateRationFeeds(Form1 frm)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
double Quantity = Convert.ToDouble(frm.RationFeedsdataGridView.CurrentCell.Value);
string FeedName = frm.RationFeedsdataGridView.CurrentRow.Cells[1].Value.ToString();
Connection.Open();
Cmd.CommandText = "Update SelectedFeeds set Quantity=@quantity Where SelectedFeeds.[Feed Name]=@feedname";
Cmd.Parameters.Add("@quantity", OleDbType.Double).Value = Quantity;
Cmd.Parameters.Add("@feedname", OleDbType.LongVarChar).Value = FeedName;
Cmd.ExecuteNonQuery();
Connection.Close();
}