Automatic postback: Give error the variable name has already been declared - c#

I'm trying to bind telerik autocomplete textbox from mssql database using asp c#.net.
<telerik:RadAutoCompleteBox AllowCustomEntry="true" ID="RadAutoCompleteBox2" runat="server" InputType="Text">
<TextSettings SelectionMode="Single" />
</telerik:RadAutoCompleteBox>
And my .aspx.cs file's code is given below
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)
{
}
}
When I remove Parameters, code working properly but in parameters line I'm still getting error.
The variable name #cityname has already been declared. Variable names must be unique within a query batch or stored procedure.
I'm getting error because when I press any key telerik autosuggesbox automatically postback and bind data again and again.

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)
{
}
}

Related

asp.net linq query datatable

I have been following this tutorial to implement edit/update functionality via a modal popup form in asp.net:
http://msdnaspdotnettuto.blogspot.com/2015/01/aspnet-gridview-crud-using-twitter.html
This is my code:
public partial class GroupSummary1 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGroupSummary();
}
}
private void LoadGroupSummary()
{
try
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}
protected void gvGroupSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("detail"))
{
string code = gvGroupSummary.DataKeys[index].Value.ToString();
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
}
When I select the "detail" button on the grid view, the following error occurs:
System.ArgumentNullException HResult=0x80004003 Message=Value
cannot be null. Parameter name: source Source= StackTrace:
At this line:
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
The dt object is NULL and I suspect this is the source of the problem. However, I have declared it above just as in the tutorial.
Any ideas?
Thanks
LoadGroupSummary is only firing on initial page load, not on postback. Clicking your detail button to call gvGroupSummary_RowCommand() will cause a postback.
Simply remove the if (!IsPostBack) from your page load.
protected void Page_Load(object sender, EventArgs e)
{
LoadGroupSummary();
}
EDIT:
Might be worth mentioning that if whatever data userBLL.GetGroupSummary() returns is static, you should probably only load it once. For Example:
private void LoadGroupSummary()
{
try
{
if (Session["GroupSummary"] != null)
{
dt = (DataTable)Session["GroupSummary"];
}
else
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
Session["GroupSummary"] = dt;
}
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}

Asp.net listview does not display data correctly

My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load

Having trouble populating my drop down list from informix DB

Can't Populate the dropdown list . Can anyone help , possibly some tutorials on my mistakes? I don't understand exactly how to populate my datasource. Pretty new to C# or ASP.Net so go easy on me.
protected void Button1_Click(object sender, EventArgs e)
{
List<string> _newList = new List<string>();
if (TextBox1.Text != null)
{
OdbcDataReader MapResult; //Data Reader
Database db = new Database();
string lat = "";
string sql = " SELECT
informix.dbimg_mstr_rec.doc_path
FROM
informix.dbimg_mstr_rec
WHERE
informix.dbimg_mstr_rec.doc_key
= '" + TextBox1.Text + "'";
try
{
MapResult = db.ExecQuery(sql, timeOut);
if (MapResult.Read())
{
lat = MapResult["doc_path"].ToString();
DropDown1.DataSource = _newList;
DropDown1.DataTextField = "doc_path";
DropDown1.DataValueField = "doc_path";
form1.Controls.Add(DropDown1);
} //end if
MapResult.Close();
db.CloseConnection();
//end while
}//end try
catch (OdbcException ex)
{
errList.Add("[User] Error 109: " + ex.Message);
} //end catch
return;
} //end if
else
return;
}
It doesn't look like you're actually binding the dropdown anywhere in this code. You need to do something like this:
DropDown1.DataTextField = "doc_path";
DropDown1.DataValueField = "doc_path";
DropDown1.DataSource = dr.ExecuteReader();
DropDown1.DataBind();
Alternately, you can do this all in your page markup by using a SqlDataSource control.
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
DataSourceMode="DataSet"
ConnectionString="myConnString"
SelectCommand="myStoredProcedure"
>
</asp:SqlDataSource>
<asp:MyDropDownList id="DropDown1" runat="server" DataSource="SqlDataSource1"
DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" />

Two dropdown in a page ( conflict )

Two dropdownlists drop1, drop2 have separate selected index changed. Any dropdown, on selectedindexchanged, goes to another page. If we use back button in browser it goes back to our home page and one of dropdown will be selected position. If we change the other dropdown, it works only the first selected index changed in the coding section
How can we solve this problem?
code
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
string zCenterId="0";
if(Request.QueryString["LCID"]!=null)
{
zCenterId = Request.QueryString["LCID"].ToString();
}
ManageActivityAdminUIController ObjCtrl = new ManageActivityAdminUIController();
List<ManageActivityAdminUIInfo> ObjInfo = ObjCtrl.GetActivityList(zCenterId );
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataBind();
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataTextField = "ActivityName";
drplistactivity.DataValueField = "ID";
drplistactivity.DataBind();
drplistactivity.Items.Insert(0, new ListItem("<--Select Activity-->", "0"));
ManageCoursesController ObjCtrl = new ManageCoursesController();
List<ManageCoursesInfo> ObjInfo = ObjCtrl.GetCourses(zCenterId );
drplistcourse.DataSource = ObjInfo;
drplistcourse.DataTextField = "CourseName";
drplistcourse.DataValueField = "ID";
drplistcourse.DataBind();
drplistcourse.Items.Insert(0, new ListItem("<--Select Course-->", "0"));
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void drplistactivity_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Activity.aspx?ActivityId="+drplistactivity.SelectedItem.Value);
Response.Redirect(url);
}
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
If ViewState is off (on the dropdown or any of its parents - all the way up to the page) then the event won't fire. (It should post back though...)
The problem seems to be caused by the caching of your page.
I'd say that your two events are triggered, but you can not see it because of redirect
You may disable caching of your form :
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Expires = -1;
or you may test the eventtarget inside your eventhandlers
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
if(drplistcourse.UniqueID!=Request.Form["__EVENTTARGET"])
return;
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}

Deleting 11th row in RadGrid makes it become blank

I have one Telerik RadGrid. Using a method I am filling the grid. I have enabled the paging property. I have used ItemTemplate-->ImageButton for delete and edit options. I have set page size as 10. Page load time is working properly and populating the grid. After inserting the 11th row the pagination starts and it will show in the next page with one record. But when I am deleting the 11th row the grid becomes blank. I have used dataset to bind the records.
radgrid.DataBind();
dsDataset.Dispose();
But its item.count is 0. What is the reason?
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
PopulatePackage();
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
protected void gvPackage_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = dsPackage.Tables[0];
dsPackage.Dispose();
//PopulatePackage();
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
private void PopulatePackage()
{
try
{
lblMessage.Text = string.Empty;
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = null;
gvPackage.DataSource = dsPackage.Tables[0];
gvPackage.DataBind();
//dsPackage.Dispose();
if (gvPackage.Items.Count <= 0)
{
lblMessage.Text = "No Package Details Found...";
gvPackage.Visible = false;
}
else
{
gvPackage.Visible = true;
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
Okay as far as I am understanding it, You have a radgrid in which you have allowed paging and set the page size to 10. Upon inserting the 11th record a new page is shown with that 11th record. And when that 11th record is deleted you are viewing a blank page, instead of showing the page having record from 1 to 10. I hope I am right here.
Anyway. I guess the problem is that the Radgrid is not having the data for the page you are viewing now.
There is an event in RadGrid named NeedDataSource. This Event is fired up whenever the RadGrid needs to display the data. You can call the Binding logic in this event and see if it works for you.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
RadGrid1.DataSource = "BindingSource";
RadGrid1.DataBind();
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
BindGrid();
}
See if this works for you..

Categories

Resources