我有一个网页,我的数据访问层我正在将文本框更新到我的页面。这是一个简单的3层应用程序。
我在DataAccess类中有这样的东西:
public void SaveDataSet(DataTable table)
{
//What to do here???
}
我应该如何将所有文本框值作为DataTable参数传递给此函数?
答案 0 :(得分:1)
答案 1 :(得分:1)
或者,如果你想要数据表的方式,你需要这样的东西
首先我们创建数据表
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
然后您需要一种方法将数据插入数据表
private void AddDataToTable(string username,string firstname,string lastname,DataTable myTable)
{
DataRow row;
row = myTable.NewRow();
row["id"] = Guid.NewGuid().ToString();
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
现在你可以创建一个方法来将数据表插入到sql server中,就像这样
private void insertDataTable(DataTable MyDataTable)
{
string ConnectionString = "your connection string";
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(ConnectionString)
{
bulkcopy.DestinationTableName = “dbo.<your table>”;
try
{
bulkcopy.WriteToServer(MyDataTable);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}