使用asp.net中的会话传递datalist值

时间:2015-03-25 16:44:56

标签: c# asp.net session datalist

我实际上是使用会话存储一个值,然后使用图像按钮重定向到其他页面,其中基于会话值我从数据库中获取数据。我在行中得到了一个用户定义的异常。 请帮忙!

adap.Fill(dt1);//[SqlException (0x80131904): Incorrect syntax near '='.]

这是我的编码。

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    ImageButton btn = sender as ImageButton;
    string modelId = btn.CommandArgument;
    Session["modelid"] = modelId;
    Response.Redirect("details.aspx");
} 

public partial class details : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=" + Session["modelid"], con);
        DataTable dt1 = new DataTable();
        adap.Fill(dt1);
        DataList1.DataSource = dt1;
        DataBind();
    }

2 个答案:

答案 0 :(得分:0)

首先将会话对象转换为字符串。

(String) Session["modelid"] 

答案 1 :(得分:0)

我建议您avoid using string concatenation创建命令 - 改为使用parameters

此外,您必须检查Session["modelid"]是否具有值,因为具有空值的参数将完全导致给定的消息:

  

参数化查询'(@ id nvarchar(4000))从details1中选择*   其中Modelid = @ id'期望参数' @ id',这是未提供的

所以,代码将是:

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();

    var id = Session["modelid"];

    if (id != null)
    {        
        SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=@id" , con);
        adap.SelectCommand.Parameters.AddWithValue("@id", );

        DataTable dt1 = new DataTable();
        adap.Fill(dt1);
        DataList1.DataSource = dt1;
        DataBind();
    }
}

如果可以保证在第一次回发后设置Session["modelid"],则使用Page.IsPostBack属性。

或者只是使用一些默认值。

P.S。:此外,not a good idea使用实例级连接,您无法以确定的方式Dispose (Close)。最好使它成为方法级变量,并将其与using子句一起使用:

protected void Page_Load(object sender, EventArgs e)
{
     using (SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True"))
     {
         // ...        
     }
}