2017-03-15 32 views
-1

我试图从asp c#.net从mssql数据库绑定telerik自动完成文本框。下面自动回发:给出错误的变量名已被声明

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 [email protected]"; 
     SqlDataSource1.SelectParameters.Add("@cityname", Request.QueryString["city"].ToString()); 
     RadAutoCompleteBox2.DataSourceID = "SqlDataSource1"; 
     RadAutoCompleteBox2.DataTextField = "citylocation"; 
     RadAutoCompleteBox2.DataBind(); 
    } 
    catch (Exception ex) 
    { 
    } 
} 

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

而且我.aspx.cs文件的代码被给予当我删除参数,代码工作正常,但是在参数行,我仍然得到错误。

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

我得到错误,因为当我按任何键时,自动回发和绑定数据一次又一次。

+0

由标题,它看起来像一个[复制](http://stackoverflow.com/search?tab=relevance&q=%22The%20variable%20name%22%20%22has%20already%20been%20declared% 22%5BC%23%图5d)。但是一个简单的'if(!IsPostBack)'应该可以做到。你的问题是基本的,你应该只做第一次[页面加载](https://msdn.microsoft.com/en-us/library/ms178472.aspx#general_page_lifecycle_stages) –

回答

0
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 [email protected]"; 
     SqlDataSource1.SelectParameters.Add("@cityname", _city); 
     RadAutoCompleteBox2.DataSourceID = "SqlDataSource1"; 
     RadAutoCompleteBox2.DataTextField = "citylocation"; 
     RadAutoCompleteBox2.DataBind(); 
    } 
    catch (Exception ex) 
    { 

    } 

}