|
-
May 1st, 2007, 10:59 PM
#1
Thread Starter
Fanatic Member
{RESOLVED} Dropdownlist in C# (ASP.NET)
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.
Code:
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 **
Last edited by Wen Lie; May 3rd, 2007 at 11:49 PM.
Reason: Problem Solved...
Regards,
[-w-]
-
May 2nd, 2007, 10:35 PM
#2
I wonder how many charact
Re: Dropdownlist in C# (ASP.NET)
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:
Code:
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();
}
}
-
May 3rd, 2007, 11:48 PM
#3
Thread Starter
Fanatic Member
Re: Dropdownlist in C# (ASP.NET)
wooohoooo..
Thanks Nemaroller ...
it helps and works
^_^
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|