【问题标题】:Automatic postback: Give error the variable name has already been declared自动回发:给错误变量名已经被声明
【发布时间】:2017-03-15 09:27:18
【问题描述】:

我正在尝试使用asp c#.net 绑定来自 mssql 数据库的 Telerik 自动完成文本框。

<telerik:RadAutoCompleteBox AllowCustomEntry="true" ID="RadAutoCompleteBox2" runat="server" InputType="Text">
    <TextSettings SelectionMode="Single" />
</telerik:RadAutoCompleteBox>

我的 .aspx.cs 文件的代码如下所示

protected void Page_Load(object sender, EventArgs e)
{
    try
    {   
        SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        this.Page.Controls.Add(SqlDataSource1);
        SqlDataSource1.ConnectionString = "my connection";
        SqlDataSource1.SelectCommand = "select citylocation from citylocationtbl where cityname=@cityname";
        SqlDataSource1.SelectParameters.Add("@cityname", Request.QueryString["city"].ToString());
        RadAutoCompleteBox2.DataSourceID = "SqlDataSource1";
        RadAutoCompleteBox2.DataTextField = "citylocation";
        RadAutoCompleteBox2.DataBind();
    }
    catch (Exception ex)
    {
    }
}

当我删除参数时,代码可以正常工作,但在参数行中我仍然遇到错误。

变量名@cityname 已经被声明。变量名称在查询批处理或存储过程中必须是唯一的。

我收到错误消息,因为当我按下任何键时,telerik autosuggesbox 会自动回发并一次又一次地绑定数据。

【问题讨论】:

  • 从标题来看,它看起来像duplicate。但是一个简单的if (!IsPostBack) 应该可以解决问题。您的问题基本上是您应该只在第一次使用 Page Load 时执行此代码

标签: c# asp.net sql-server telerik


【解决方案1】:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadCity(Request.QueryString["city"].ToString());
    }

}

protected void LoadCity(string _city)
{
    try
    {
        SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        this.Page.Controls.Add(SqlDataSource1);
        SqlDataSource1.ConnectionString = "my connection";
        SqlDataSource1.SelectCommand = "select citylocation from citylocationtbl where cityname=@cityname";
        SqlDataSource1.SelectParameters.Add("@cityname", _city);
        RadAutoCompleteBox2.DataSourceID = "SqlDataSource1";
        RadAutoCompleteBox2.DataTextField = "citylocation";
        RadAutoCompleteBox2.DataBind();
    }
    catch (Exception ex)
    {

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2019-10-10
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多