这是我的搜索功能与gridview.I'我无法在表单中获得gridview仍然很好。我在这里添加了新的第二列。请帮助我。谢谢
private void txtSearch02()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode='" + txtkey2.Text.Trim() + "') or (ItemName is null or ItemName='" + txtkey2.Text.Trim() + "')", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["ItemCode"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
con.Close();
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//dt.Rows[0]["Quantity"].ToString();
//dt.Rows[0]["TotalPoints"].ToString();
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
答案 0 :(得分:0)
如果你有前三列(带有bindvalue)并添加其他两列,那么它会让人感到困惑。 再次将所有列添加到datatable。意味着三个和两个新的。
试试吧。它应该工作。因为你的代码是正确的。
答案 1 :(得分:0)
答案 2 :(得分:0)
继续我关于参数化查询和使用'using(){}'语句的评论后,我首先写下这样的内容:
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(myStr))
{
string sql = "select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode = @txtkey2) or (ItemName is null or ItemName = @txtkey2)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@txtkey2", txtkey2.Text.Trim());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//You're currently adding a blank DataTable to a session variable below as you've not
//filled it yet. I've left this incase that's what you meant to do.
Session["ItemCode"] = dt;
con.Open();
//SqlDataAdapter should be able to fill a DataTable as well as a dataset.
sda.Fill(dt);
if (dt.Rows.Count > 0) //Put a breakpoint here to check if anything is returned in dt
{
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//Not sure what you're trying to do here. You're just adding a blank row to dt.
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
else
{
//Code to handle nothing being returned.
}
}