数据集不会更新C#中的任何内容

时间:2014-03-10 20:30:03

标签: c# ado.net dataset sqlcommandbuilder

我已经在ms-sql中编写了这个程序

ALTER proc [dbo].[gravacliente]
AS
SELECT
    idcliente, Nome, Endere, tel_empresa, celular,
    UF, CEP, Email, Contato, Referencia, OBS, Nasc,
    cpf, cnpj, Iest
FROM
    tbcliente

和这段代码

DataSet grava = new DataSet();
SqlDataAdapter da2 = new SqlDataAdapter();
SqlCommandBuilder constru6 = new SqlCommandBuilder(da2);
SqlCommand llena8 = new SqlCommand("gravacliente", conec1);
llena8.CommandType = CommandType.StoredProcedure;
da2.SelectCommand = llena8;
da2.Fill(grava, "tbcliente");
DataRow dr = grava.Tables["tbcliente"].NewRow();
dr.BeginEdit();
dr["nome"] = txtNome.Text;
dr["endere"] = txendere.Text; 
dr.EndEdit();
da2.Update(grava.Tables["tbcliente"]);
label9.Text = txtNome.Text;

conec1正在运行,但上面的代码没有更新任何内容。错误在哪里?

2 个答案:

答案 0 :(得分:1)

首先,您必须将行添加到表中。

DataRow dr = grava.Tables["tbcliente"].NewRow();

dr["nome"] = txtNome.Text;
dr["endere"] = txendere.Text; 

grava.Tables["tbcliente"].AddRow(dr);

此外,AFAIK,SqlCommandBuilder将无法使用存储过程。您必须向适配器提供更新命令或使用基于文本的选择命令:

SqlCommand llena8 = new SqlCommand("SELECT idcliente, Nome, Endere, tel_empresa, celular, UF, CEP, Email, Contato, Referencia, OBS, Nasc, cpf, cnpj, Iest FROM tbcliente", conec1);

当然,您还需要在进行更新之前调用它:

constru6.GetUpdateCommand();

我的建议是你根本不使用SqlCommandBuilder,因为它需要额外的开销。如果你坚持使用它,我建议你read the documentation

答案 1 :(得分:0)

您需要在SqlDataAdapter

的参数中提供有效的选择
string sql = @"
SELECT
    idcliente, Nome, Endere, tel_empresa, celular,
    UF, CEP, Email, Contato, Referencia, OBS, Nasc,
    cpf, cnpj, Iest
FROM
    tbcliente
";
SqlConnection conn = new SqlConnection("Your connection string");
DataSet grava = new DataSet();
SqlDataAdapter da2 = new SqlDataAdapter(sql, conn);
SqlCommandBuilder constru6 = new SqlCommandBuilder(da2);

这是基于SqlDataAdapter的构造函数,它接受一个字符串供选择,以及一个连接。 http://msdn.microsoft.com/en-us/library/w2d3kh8d(v=vs.110).aspx

本网站有一个关于使用SqlDataAdapterSqlCommandBuilder

的绝佳参考实现

http://www.dotnetperls.com/sqlcommandbuilder

msdn中类的典型示例也非常相似。 SqlCommandBuilder Example