我正在使用一个小应用程序,用户可以从SQL中检索特定数据,用数据填充数据网格。用户可以从SQL数据库中检索数据,然后在文本框中写入条形码,然后搜索他搜索的数据。
到现在为止我使用了这段代码
if (e.Key == Key.Enter)
{
SqlConnection con = new SqlConnection("Server = localhost;Database = Bilanc; Integrated Security = true");
SqlCommand cmd = new SqlCommand("product", con); // Using a Store Procedure.
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("dtList");
cmd.Parameters.AddWithValue("@Barcod", txtcode.Text);
DataTable dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();//Made a new DataColumn to populate above DataTable
dc.DataType = System.Type.GetType("System.String");//Defined the DataType inside, this can be [[int]] if you want.
dc.ColumnName = "@Barcod";//Gave it a name (important for the custom expression - can only be one word so use underscores if you need multiple words)
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.String");
dc2.ColumnName = "@Product";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "@QTY";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "@Price";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.ColumnName = "@Tax";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "@Price * @QTY";//Multiplying the Price and Quantity DataColumns
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc2);
dataTable.Columns.Add(dc3);
dataTable.Columns.Add(dc4);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtg.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
con.Open();//Open the SQL connection
SqlDataReader reader = cmd.ExecuteReader();//Create a SqlDataReader
while (reader.Read())//For each row that the SQL query returns do
{
DataRow dr = dataTable.NewRow();//Create new DataRow to populate the DataTable (which is currently binded to the DataGrid)
dr[0] = reader[0];//Fill DataTable column 0 current row (Product) with reader[0] (Product from sql)
dr[1] = reader[1];
dr[2] = reader[2];
dr[3] = reader[3];
dr[4] = reader[4];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
}
}
代码工作正常,但是当我遇到困难时,当我从SQL检索数据时,新数据会覆盖以前的数据。 我的问题是如何保留以前的数据 谢谢大家
答案 0 :(得分:0)
尝试使用InsertAt()方法代替具有适当位置参数的数据表的Add()。