将数据提取到标签asp.net

时间:2016-06-07 13:12:31

标签: c# asp.net label

这是我的历史页面:

enter image description here

代码背后的代码:

public static string cs = "Server=PAULO;Database=ShoppingCartDB;Integrated Security=true";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["New"] != null)
        {
            if (!IsPostBack)
            {
                SqlConnection con = new SqlConnection(cs);
                con.Open();

                string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] +"'";
                SqlDataAdapter da = new SqlDataAdapter(sql, con);
                DataTable dt = new DataTable();
                da.Fill(dt);




                Label2.Text += Session["New"].ToString();
                linkLogout.Visible = true;
                //linkOrderHistory.Visible = true;
                Label2.Visible = true;
                linkViewProfile.Visible = true;
                grid.DataSource = dt;
                grid.DataBind();
            }
        }

    }
    private void CustomBindData()
    {
        SqlConnection con = new SqlConnection(cs);
        con.Open();

        string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] + "'";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);

        grid.DataSource = dt;
        grid.DataBind();
    }

当我点击“查看详细信息”时,它显示了我:

enter image description here

我想要的是获取会话ID和ID并将其放入我的标签中。到目前为止我得到了这个:

string strConnString = "Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True";
    string str;
    SqlCommand com;
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        str = "select Id from CustomerDetails Where CustomerName = '"+Session["New"].ToString()+"'";
        com = new SqlCommand(str, con);
        SqlDataReader reader = com.ExecuteReader();

        if (!IsPostBack)
        {
            reader.Read();
            Label3.Text = reader["Id"].ToString();
            Label2.Text = Session["New"].ToString();

会话很好(“faufao”)并且在我的标签中有一些值(“13”): enter image description here

但是当我尝试点击Id 22时,它仍会显示Id 13?对此有什么诡计吗?

顺便说一下这是我的数据库: enter image description here

目前,我得到了这个:

enter image description here

我错过了什么?谢谢

1 个答案:

答案 0 :(得分:0)

str = "select Id from CustomerDetails Where CustomerName = '"+Session["New"].ToString()+"'";

此查询将返回许多id。因此,当您撰写Label3.Text = reader["Id"].ToString()时,它将返回第一行(13)

您首先阅读所有id并将其列入列表并使用它们。

List<string> ListOfId = new List<string>();
While( reader.Read())
{
    ListOfId.Add( reader["Id"].ToString());
}

更好的做法是使用id

获取QueryString
Label3.Text =  Request.QueryString[0];

Label3.Text =  Request.QueryString["Id"];