且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将gridview数据保存到具有下拉列表的数据库中。

更新时间:2023-01-12 11:55:15

我对你的错误提出了建议。你提到错误来自以下行:



I have a suggestion regarding your error. You mention the error is coming from the following line:

id = int.Parse(g1.Cells[1].Text);





也许将Parse更改为TryParse以捕获任何数据错误,如下所示:





Maybe change the Parse to a TryParse to catch any data errors, like the following:

if(int.TryParse(g1.Cells[1].Text, out id))
{ 
    a1 = box2.SelectedValue.ToString();
    a2 = box3.SelectedValue.ToString();
    a3 = box4.SelectedValue.ToString();
    SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[class7]([IdNo],
        [SectionNo],[Date],[math],[science],[social]) VALUES
        (" + id + "," + sect + ",getdate(),'" + a1 + "','" + a2 + "','"  
        + a3 + "')", con);
    cmd.ExecuteNonQuery();
}





由于用户错误,当一个非整数放入该单元格时,上述应该使应用程序不会崩溃。至于从网格视图存储数据的更广泛问题,它取决于您的需求。为了获得***性能,您可能会考虑使用数据的本地副本,而不是为每行单独访问数据库(即,将gridview的数据源设置为等于本地副本,然后使用本地副本更新数据库)根据需要提供数据)。本地副本可以使用EntityFramework,LinqToSql,ADO.NET(DataSet,DataTable等),甚至是简单的集合(例如,StudentInfo的通用List,包含您要保留的信息的类)。



但是,如果应用程序仅供内部使用,并且您没有重大数据库问题,则可能无需进行任何操作变化。这一切都取决于你的需求。



祝你好运!



The above should keep the application from crashing when a non-integer is put into that cell due to user error. As for the broader issue of storing the data from the grid view, it depends on your needs. For best performance, you might think about working with a local copy of the data rather than making separate trips to the database for each row (i.e., set the data source of the gridview equal to the local copy, then update the database with the local data as needed). The local copy could use EntityFramework, LinqToSql, ADO.NET (DataSet, DataTable, etc.), or even a simple collection (e.g., a generic List of StudentInfo, a class containing the info you want to keep).

However, if the application is just for internal use, for instance, and you don''t have major database issues, then there may be no need to make any changes. It all depends on your needs.

Best of luck!