PDA

Click to See Complete Forum and Search --> : {RESOLVED} Dropdownlist in C# (ASP.NET)


Wen Lie
May 1st, 2007, 10:59 PM
:wave:
Hello...

I'm a bit confuse about the dropdownlist usage in C#.
I've created a dropdownlist object (name = DDlist) and a command button object (name = cmdButton).

And I've written below code in the .aspx.cs.

public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s_Conn = "server=myServer; user id=myID; password =myPwd; database=myDatabase";
string s_Query = "select login from pwdps order by login asc";
System.Data.SqlClient.SqlConnection myCn = new System.Data.SqlClient.SqlConnection(s_Conn);
System.Data.SqlClient.SqlCommand myCmd = new System.Data.SqlClient.SqlCommand(s_Query, myCn);

myCn.Open();
myCmd.CommandType = CommandType.Text;

System.Data.SqlClient.SqlDataReader myDR = myCmd.ExecuteReader();

DDlist.DataSource = myDR;
DDlist.DataValueField = "login";
DDlist.DataBind();
}

protected void cmdButton_Click(object sender, EventArgs e)
{
Response.Write("Hello " + DDlist.SelectedItem.Text);
}
}


Each time I choose an item from that dropdownlist, and press a command button, I wish the text of selected item can be written.
But, the result is not the same with what I've expected.

The code (at cmdButton_Click) always return the first item of the dropdownlist.

e.g :
the list of DDlist contain :
-Andi
-Budi
-Charles
-Natasha

even I choose Charles, the code will return "Hello Andi".

Do I miss some codes here ?

Thanks
** Willy **

nemaroller
May 2nd, 2007, 10:35 PM
Yes, you missed something - but its not entirely the first time someone has done it, and of course its the simplest of things.

You are rebinding the dropdownlist on every post-back - so of course it will always show the first item.

You want to wrap that code in a:

protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
string s_Conn = "server=myServer; user id=myID; password =myPwd; database=myDatabase";
string s_Query = "select login from pwdps order by login asc";
System.Data.SqlClient.SqlConnection myCn = new System.Data.SqlClient.SqlConnection(s_Conn);
System.Data.SqlClient.SqlCommand myCmd = new System.Data.SqlClient.SqlCommand(s_Query, myCn);

myCn.Open();
myCmd.CommandType = CommandType.Text;

System.Data.SqlClient.SqlDataReader myDR = myCmd.ExecuteReader();

DDlist.DataSource = myDR;
DDlist.DataValueField = "login";
DDlist.DataBind();
}
}

Wen Lie
May 3rd, 2007, 11:48 PM
wooohoooo..
Thanks Nemaroller ...
it helps and works
^_^