【发布时间】:2016-04-01 19:49:45
【问题描述】:
我正在尝试将表格从工具的 gridview 更新到 SQL 数据库。问题是它没有在数据库中更新。
下面是我更新数据库的按钮点击代码: 在调试代码时,我发现数据表 DT 只获取源值而不是网格视图中的更新值....
网格视图中是否有任何属性可以接受这些更改并更新 DT 表?
public partial class BusinessRules : Form
{
//Declaration Part
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");
private string sqlconn; // query and sql connection
private SqlDataAdapter SDA = new SqlDataAdapter();
DataTable DT = new DataTable();
SqlCommandBuilder scb = new SqlCommandBuilder();
private void button_retreive_Click(object sender, EventArgs e)
{
string commandText = "CoSD.RetreiveBusinessRulesTool";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
cmd.Parameters.Add("@CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
try
{
con.Open();
SDA.SelectCommand = cmd;
DT = new DataTable();
SDA.Fill(DT);
int count1 = DT.Rows.Count;
if (DT.Rows.Count > 0)
{
dataGridView.DataSource = DT;
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Business Rules Found");
}
}
catch (SqlException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
scb = new SqlCommandBuilder(SDA);
SDA.Update(DT);
// confirm
MessageBox.Show("Updates successfully submitted to CoSD");
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
【问题讨论】:
-
1. 为什么保存的时候要设置grid的数据源? 2. 如何创建
SDA数据适配器?请将其代码添加到问题中。 3. 如何填写和编辑DT数据表。请将其代码添加到问题中。 -
@RezaAghaei...您好我已经编辑了问题请检查代码现在...
-
您可能会发现this post 很有帮助。
-
@RezaAghaei...谢谢...我试过了,但没用...问题是从存储 SP 的输出到数据表,然后我正在尝试使用 gridview 中显示的列更新表...显示的代码不起作用...
-
我还使用存储过程测试了链接的答案,它工作正常。
标签: c# .net winforms datagridview windows-applications