我有一个select语句,它从表1中选择记录并显示在datagridview中,
如何将datagridview中显示的数据复制到select语句之后的table2。
下面是我从表1中选择项目的代码
public void getdata(){
if (txt_Barcode.Text== "" )
{
MessageBox.Show ("Please fill in something");
}
for (int i = 0; i < dgv_Detail.Rows.Count +1; i++)
{
da = new SqlDataAdapter("select * from asset where asset_no='" + txt_Barcode.Text + "'", conn);
}
da.Fill(Assetdt);
}
#endregion
public void fillds()
{
dgv_Detail.DataSource = Assetdt;
}
激活事件
private void txt_Barcode_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
getdata();
fillds();
insertbar();
}
}
有人不知道怎么做吗?
最佳答案
首先将数据从数据网格视图移动到数据表:
DataTable dt = new DataTable();
DataColumn[] dcs = new DataColumn[]{};
foreach (DataGridViewColumn c in dgv.Columns)
{
DataColumn dc = new DataColumn();
dc.ColumnName = c.Name;
dc.DataType = c.ValueType;
dt.Columns.Add(dc);
}
foreach (DataGridViewRow r in dgv.Rows)
{
DataRow drow = dt.NewRow();
foreach (DataGridViewCell cell in r.Cells)
{
drow[cell.OwningColumn.Name] = cell.Value;
}
dt.Rows.Add(drow);
}
然后使用datable.rows上的foreach循环将数据从data table移动到sql table,如下所示:
foreach(DataRow dr in dt.Rows)
{
Product product = new Product(); // make seperate class with same feilds as sql table
//Get the column values
product.productId = dr["productId"];
product.productName = dr[ProductName"];
Product.Insert();//Insert will have inserting records into the dabtase
}
产品分类如下:
public class Product
{
public int productId { get; set; }
public string productName { get; set; }
}