我是.net的新手。我已经在SQL Server中创建了一个表,该表通过Windows From上的dataGridView显示。我希望使更改直接适用于Windows Form的数据表。为此,我使用了dataAdapter和dataCommandBuilder变量。
我面临以下问题:
我的代码:
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
private void Refresh()
{
string con = null;
SqlConnection connect;
con = @"Server =Hassan; Database =FBT; Integrated Security =SSPI;";
connect = new SqlConnection(con);
sda = new SqlDataAdapter(@"SELECT * FROM Contact_Person", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button9_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
private void button8_Click(object sender, EventArgs e)
{
Refresh();
}
我认为如果可以手动设置Update函数,则可以将其定向到我执行的过程中,可以解决我的问题。
[下面的图片是我的代码,函数前面写的数字表示调用顺序]
答案 0 :(得分:0)
DataGridView具有绑定或取消绑定所需列的几种功能,但是由于您需要更新的主键,因此我建议使用Visibility
,请参见下文:
从数据库中获取查询后,使用其数据源又将其绑定到DataGridView,dataGridView1.DataSource = dt;
将主键字段的可见性设置为false,如下所示:
dataGridView1.Columns["PrimaryKey"].Visibility = false;
而且由于我不知道您的存储过程,所以我不太明确,但这是您更新字段的方式。
using (SqlConnection conn = new SqlConnection("Server =Hassan; Database =FBT; Integrated Security =SSPI;"))
using (SqlCommand cmd = new SqlCommand("StoredProcedure", conn))
{
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
//you should know whats the type of your primary key i assumed its int
adapt.SelectCommand.Parameters.Add(new SqlParameter("@PrimaryKey", SqlDbType.Int));
adapt.SelectCommand.Parameters["@PrimaryKey"].Value = PrimaryKey;
//lets assume you are updating a Name which is string then
adapt.SelectCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["@Name"].Value = Name;
conn.Open();
cmd.ExecuteNonQuery();
}
更新
您的SQL存储过程将如下所示:
CREATE Procedure ProcedureName
(
@PrimaryKey Int,
@Name varchar(50)
)
AS BEGIN
UPDATE TABLENAME
SET Name = @Name
Where PrimaryKey = @PrimaryKey
END