【问题标题】:use datagridview to show 2 tables' data for updates in c# winform使用datagridview在c#winform中显示2个表的更新数据
【发布时间】:2013-06-23 14:01:17
【问题描述】:

现在我正在制作一个 C# winForm,我必须使用网格来显示从两个表中检索到的数据以供用户编辑。

表格如下。

学生桌:

id int
name char(10)

主题表:

id int
name char(10)

学生科目表:

id int (Pri key, AUTO_INCREMENT)
student_id int 
subject_id int 
mark int

winform 中的网格会显示某个学生的科目,例如id = 12345,使用如下 SQL:

select studentsubject.id, subject.name, studentsubject.mark
from subject, studentsubject
where studentsubject.student_id = 12345
and studentsubject.subject_id = subject.id

检索到的这些数据被放入一个数据集,然后放入一个网格中,第一列 (studentsubject.id) 被隐藏。

我使用 datagridview 来做到这一点,并且可以让用户更改标记、为新主题添加新行以及通过删除 datagridview 中的一行来删除主题。

但问题是如何将网格中的数据更改回数据库。

我应该使用数据网格来代替吗??

谢谢

【问题讨论】:

标签: c# winforms datagridview


【解决方案1】:

以下是与您的要求相对应的 UPDATE、INSERT 和 DELETE 命令:

update studentsubject 
set mark = @mark

insert into [subject] (name) 
values (@name); 
insert into studentsubject (student_id, subject_id, mark) 
values (1, @@identity, @mark)

declare @subject_id int; 
select @subject_id = subject_id 
from studentsubject 
where id = @id; 
delete from studentsubject 
where id = @id; 
delete from [subject] 
where id = @subject_id

我建议您使用SqlDataAdapter 执行更新,因为它可以根据DataRow 的状态自动决定执行哪个操作。您只需要执行SqlDataAdapter.Update 方法。当然SqlDataAdapter.DeleteCommandSqlDataAdapter.InsertCommandSqlDataAdapter.UpdateCommand属性必须赋值。

这是一个代码sn-p:

adapter.InsertCommand = connection.CreateCommand();
adapter.InsertCommand.CommandText = "insert into [subject] (name) values (@name); insert into studentsubject (student_id, subject_id, mark) values (1, @@identity, @mark)";
adapter.InsertCommand.Parameters.AddRange(new SqlParameter[] {
    new SqlParameter("@name", SqlDbType.Char, 10, "name"),
    new SqlParameter("@mark", SqlDbType.Int, 1, "mark")
});
adapter.UpdateCommand = connection.CreateCommand();
adapter.UpdateCommand.CommandText = "update studentsubject set mark = @mark";
adapter.UpdateCommand.Parameters.Add("@mark", SqlDbType.Int, 1, "mark");
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = "declare @subject_id int; select @subject_id = subject_id from studentsubject where id = @id; delete from studentsubject where id = @id; delete from [subject] where id = @subject_id";
adapter.DeleteCommand.Parameters.Add("@id", SqlDbType.Int, int.MaxValue, "id");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2021-03-19
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多