1

我已经在 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正在工作,但上面的代码没有更新任何内容。错误在哪里?

4

2 回答 2

1

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

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

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

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

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

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它,因为它会产生额外的开销。但是,如果您坚持使用它,我建议您阅读文档

于 2014-03-10T20:35:28.780 回答
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 示例

于 2014-03-10T21:05:54.213 回答