基本上我正在映射字段。正如你所看到的GridView 2
我选择了特定的列名称。
让我们考虑第一条记录,即1 | id | Column0
,For id
我已选择Column0
,所以在数据库中我想在 id 列下存储列值 1,2,3,4.. 。像下面这样
id
1
2
3
所以我的问题是如何将列值存储在动态传递列名称、列值的特定列中?
这是我所做的代码,我知道它是错误的。
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dtMap = new DataTable();
dtMap.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Source", typeof(string)), new DataColumn("Destination", typeof(string)) });
foreach (GridViewRow gr in GridView2.Rows)
{
int id = Convert.ToInt32(GridView2.Rows[gr.RowIndex].Cells[0].Text);
string source = GridView2.Rows[gr.RowIndex].Cells[1].Text;
string destination = ((DropDownList)gr.FindControl("DropDownList1")).SelectedItem.Value;
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
DataColumn selectedColumn = dt.Columns[destination];
List<object> allValues = dt.AsEnumerable().Select(r => r[selectedColumn]).ToList();
connection();
strsql = "Insert into F3_BC_Product_Mapping_Data (@source) values (@value) ";
cmd = new SqlCommand(strsql, con);
cmd.Parameters.AddWithValue("@source", destination);
cmd.Parameters.AddWithValue("@value", allValues);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtMap.Rows.Add(id, source, destination);
}
我尝试了一些东西。检查一下并请告诉我。
foreach (GridViewRow gr in GridView1.Rows)
{
int id = Convert.ToInt32(GridView1.Rows[gr.RowIndex].Cells[0].Text);
string source = GridView1.Rows[gr.RowIndex].Cells[1].Text;
string destination = ((DropDownList)gr.FindControl("DropDownList1")).SelectedItem.Value;
InsertDynamicColumn(source, destination);
}
这是我的InsertDynamicColumn(string source, string destination)
方法。在我得到我的数据表之后Session
我根据目标参数过滤数据表并将结果放入新列表中。其余的很容易。将值从列表插入到源。
private void InsertDynamicColumn(string source, string destination)
{
//dt from Session
DataTable dt = new DataTable();
dt = (DataTable)Session["myData"];
//list filtered by Column name
var list = from t in dt.AsEnumerable()
select new
{
colX = t.Field<string>(destination),// "ColX"
};
//new filtered list.
var listOfColx = list.ToList();
//loop through list and insert values to source from parameters
for (int i = 0; i < listOfColx.Count; i++)
{
connection();
strsql = string.Format("Insert into F3_BC_Product_Mapping_Data ({0}) values (@value) ", source);
cmd = new SqlCommand(strsql, con);
cmd.Parameters.AddWithValue("@value", listOfColx[i]);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)