Skip to main content
 首页 » 编程设计

c#之如何在 C# 中使用 datagridview 更新 Access 数据库

2024年02月05日15qq号

我有一个 datagridview 与 datatable 绑定(bind)并使用 DataPropertyName datagridview 只显示 4 列数据库.
这就是我将 database 绑定(bind)到 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 我尝试自己使用这段代码但是好像不对,代码是:

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 错误,我不知道如何修复它。 我该怎么办?

请您参考如下方法:

感谢@LarsTech,答案是:

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(); 
}