Asp .net dropdownlist data keep load - asp.net

After I get the value show in GridView the DropDownList will contain duplicate items when I click again.
public void Page_Load(object sender, EventArgs e)
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
public void button_click(object sender, EventArgs e)
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

You should write it as:
public void Page_Load
{
if (!IsPostBack){
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
}
public void button_click
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

The Page_Load method is called each time a postback occurs (such as when you click on an ASP.NET button control). The data was already added on the first load and stored in ViewState. On the second request, it adds it again. You can detect whether you're in a postback by using the Page.IsPostBack property.
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// add items to drop down list
}
}
Side note, make sure that any objects that implement the IDisposable interface are handled properly. You need to make sure they're disposed when you're done with them to avoid hard to diagnose errors. You can either call .Dispose() on them in a finally block or you can wrap them in a using statement. Your SqlCommand, SqlConnection (this should not be a property/field)andSqlDataReaderall implementIDisposable`.

I just found the solution. Put the if(!Ispostback) in the page load statement there.

At best-guess, without compile-able code, it looks like your Dropdown List is persisted between page loads, meaning it's never going out of context (the object remains in memory). So, it is just getting appended over and over each time there is a page load. You probably want to do a check for existing values:
public void Page_Load()
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con)) {
using(SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
//Have not tested the if statement... may need to correct it.
if(!DropDownList1.Items.Contains(dr[0].ToString())) {
DropDownList1.Items.Add(dr[0].ToString());
}
}
}
}
con.Close();
}

Related

Asp.net markup file

I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..

Execute Query from another function

I want to execute a query on a button click event.
But that query is written in another function.
Here is my code, and it's not working. What is my problem?
namespace MCE_Member_Registration
{
public partial class registration_form_view : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
createform();
}
protected void createform() {
NameValueCollection nvc = Request.Form;
surname.Text = nvc["txt_surname"];
cmd.CommandText = "Insert into mce_applicants_information values(N'" + nvc["txt_surname"] + "')";
}
protected void confirm_Click(object sender, EventArgs e)
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
I'm not sure if this solves your problem. But if you really need another method to create your command, let it return it.
protected SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand("Insert into blahblah values(blahblah)", connection);
return cmd;
}
protected void Button1_Click() {
connection.Open();
GetCommand().ExecuteNonQuery();
connection.Close();
}
Note that this is not best-practise due to several reasons. The connection should be closed even if an exception occured so use using statement instead. But that would be a problem in this approach since the connection is a field.
So i would prefer the all-in-one method approach which also uses parameters tro prevent sql-injection attacks:
protected void Button1_Click()
{
ExecuteBlahBlahCommand("blahblah");
}
private void ExecuteBlahBlahCommand(string blaColumnVal)
{
const string sql = "Insert into blahblah values(#blaColumn)";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#blaColumn", blaColumnVal);
con.Open();
cmd.ExecuteNonQuery();
}
}
I suggest you to use CommandText property and not contructor, because instance of cmd is created before this code, so you adjust your property
protected void CreateQuery() {
cmd.CommandText = "Insert into blahblah values(blahblah)";
}
protected void Button1_Click() {
connection.Open();
CreateQuery();
cmd.ExecuteNonQuery();
connection.Close();
}
Answering the question itself - Any variable you declare inside a function cannot be seen outside that function. You need to declare the SqlCommand in the correct scope...
For instance:
SqlCommand cmd;
protected void CreateQuery()
{
cmd = new SqlCommand("Insert into blahblah values(blahblah),connection)";
}
protected void Button1_Click()
{
CreateQuery();
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
This will declare the variable in the class level, and be accessible to all other methods in that class.
I'll just mention that #Tim Schmelter's answer is a good solution that might better suit your needs.

asp.net gridview edit button doesn't update

When I enter new data and press update button it saves the old data (data that I want it to update).
public void fill()
{
SqlCommand cmd = new SqlCommand("select * from school ",con );
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
fill();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
string stu =((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int age = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
SqlCommand cmd = new SqlCommand("UPDATE school SET stu_name=#stu_name,age=#age where id=#id ", con);
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#stu_name", stu));
cmd.Parameters.Add(new SqlParameter ("#age",age));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fill();
}
he problem that the values that assigned to name,age are the existing values in the database not the new values which I entered in the runtime
any one can help me??
thanks in advance
You are repopulating the grid every time you edit it.
Call fill(); on grid init instead.
Here's some info on the Life Cycle of a web form. I think all you need is to wrap your fill(); in an if statement. Because page_load happens before your event handler, you reload from the db on top of the values that were entered.
if(!PostBack)
{
fill();
}

I have created a new thread and try to populate it .But the grid is not visible in browser

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ThreadStart st = new ThreadStart(Populate);
Thread td = new Thread(st);
td.Start();
}
}
private void Populate()
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("select * from dbo.sales", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
I think this is because your new thread is still fetching data when the page is rendered.
So better do it like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Populate();
}
}
private void Populate()
{
using(SqlConnection con = new SqlConnection(conStr))
{
using(SqlCommand com = new SqlCommand("select * from dbo.sales", con))
{
con.Open();
SqlDataReader rdr = com.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
Try changing the Code:
private void Populate()
{
using(var con = new SqlConnection(conStr))
{
using(var com = new SqlCommand("select * from dbo.sales", con))
{
con.Open();
com.CommandType= CommandType.Text;
using(var rdr = com.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
If it doesn't works, try to removing new thread and use delegates to call the method Populate, if you want so.
Here is a link for using Asynchronous Methods. This is not the actual thing you required,but it will give you a good insight , how to use delegates to call a method asynchronously.
For asynchronous tasks, you can use PageAsyncTask class.
In this case you must add Async="True" attribute.
<%#Page Async="True" ... %>

Asp.net repeater control data duplicated when use multiple times binding

I am using asp.net 2008 repeater control. I am trying to refresh the repeater control when a button is clicked, it shows me duplicated values, that means its appending the same values once again. Here is my code
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString);
String sql;
sql = "select * from FeeCollection Where AdminNo='"+lblstano.Text+"'";
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(sql, con);
da.Fill(ds, "FeeCollection");
dt = ds.Tables["FeeCollection"];
Repeater4.DataSource = dt;
Repeater4.DataBind();
con.Close();
}
protected void btnMedical_Click(object sender, EventArgs e)
{
LoadRepeater1();
}
I want to remove the existing data and refresh the data instead of appending.
Not sure where ds (DataSet) in instantiated. Try to instantiate the DataSet/DataTable within the LoadRepeater1() method.
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager
.ConnectionStrings["SqlServerConnection"].ConnectionString);
sql = "select * from FeeCollection Where AdminNo=#AdminNo";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#AdminNo",System.Data.SqlDbType.VarChar,20).Value=lblstano.Text;
da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
Repeater4.DataSource = dt;
Repeater4.DataBind();
}

Resources