【发布时间】:2014-03-03 19:13:24
【问题描述】:
我有一个有 3 行的表,我正在尝试使用数据表将数据插入前两行,但它正在插入这样的数据,而不是在前两行中插入,而是在其他行中插入
price qty total
--------------------
5 10 -
5 12 -
- - 50
- - 60
但我想要
price qty total
--------------------
5 10 50
5 12 60
我使用以下代码从表中选择数据而不是将数据插入表中,它正确显示数据但只是插入错误的行
int sp;
public DataTable bind1()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("select * from [order]", con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public DataTable bind2()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("insert into [order](total) values(@total)", con);
cmd.Parameters.AddWithValue("@total", sp);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
DataTable dt1 = new DataTable();
DataColumn dc = new DataColumn("total");
dt1.Columns.Add(dc);
foreach(DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
DataRow dr = dt1.NewRow();
dr["total"] = s3;
dt1.Rows.Add(dr);
}
foreach (DataRow row in dt1.Rows)
{
string s1 = row["total"].ToString();
for (int i = 0; i < dt.Rows.Count; i++)
{
sp = Convert.ToInt16(s1);
dt = bind2();
}
}
我也试过这样,但还是一样的问题
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
foreach (DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
drow["total"] = s3;
sp = s3;
dt = bind2();
}
}
【问题讨论】:
-
在执行 INSERT 之前,您的表中有哪三行??
-
我认为你需要使用更新而不是插入
标签: asp.net sql-server c#-4.0 datatable