dynamically populate dropdownlist - c#

i m using following code to populate dropdownlist dynamically...
i want that value should be the subject id and text should be the sub_desc...but code is not working the value does not contain the sub_ids...so whats wrong with the code??
(sub_id is integer field)
public void Populate()
{
string ConnectionString = (string)ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand popCmd = new SqlCommand("select sub_id,sub_desc from subject", conn);
try
{
conn.Open();
ddlSub.Items.Clear();
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = ex.ToString();
}
}
thanx...

You can set AppendDataBoundItems="true" to ensure data bound items do not clear manually inserted list items.
<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="--Select Subject--" Text="--Select Subject--" Selected="true"></asp:ListItem>
</asp:DropDownList>
You can also accomplish this in the code behind.
...
dropSub.Items.Add(new ListItem("--Select Subject--", "0"));
dropSub.AppendDataBoundItems = true;
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
...

You can add you default after databinding. You will need to insert at an index of 0 though rather than Add.

Related

Populate the DropDownList in c# with value from a specific table Database

I can't populate the DropDownList in c# with value from a specific table Database.
In this example the row value of testing in database is NULL.
I have tried this code without success.
How to do resolve this?
Can you help me?
Thank you in advance for any help, really appreciated.
My code below.
ASPX
<asp:DropDownList ID="ddlTesting" runat="server">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
CS
ddlTesting.AppendDataBoundItems = true;
string sql = String.Format(#"SELECT ");
sql += String.Format(" Testing ");
sql += String.Format(" FROM ");
sql += String.Format(" `tbl_testing` ");
sql += String.Format(" WHERE Id IN (?); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Parameters.AddWithValue("param1", Base64ForUrlDecode(Request.QueryString["sId"].ToString()));
command.CommandType = CommandType.Text;
command.Connection.Open();
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter(command);
da.Fill(ds);
ddlTesting.DataTextField = ds.Tables[0].Columns["Testing"].ToString();
ddlTesting.DataValueField = ds.Tables[0].Columns["Testing"].ToString();
ddlTesting.DataSource = ds.Tables[0];
ddlTesting.DataBind();
Response.Write(ddlTesting.Items.Count);
if (ddlTesting.Items.Count > 1)
{
ddlTesting.Items.FindByValue("Testing").Selected = true;
}
else
{
ddlTesting.SelectedValue = null;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
ddlTesting.Items.Insert(0, new ListItem("[Y/N]", ""));
ddlTesting.Items.Insert(1, new ListItem("[------------------]", "-99"));
}
}
Please, try this :
OleDbConnection conn =
new OleDbConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
try
{
conn.Open();
var cmd = new OleDbCommand("SELECT
IFNULL(Testing,'[Y/N]') AS Testing
FROM tbl_Testing
WHERE ID = #param1", conn);
cmd.Parameters.AddWithValue("param1", Request.QueryString["sId"].ToString());
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string result = reader.GetString(0);
ddlTesting.SelectedValue = result;
ddlTesting.AppendDataBoundItems = true;
}
}
}
finally
{
conn.Close();
}
Problem is with below line:
ddlTesting.Items.FindByValue("Testing").Selected = true;
Instead of using Column Name "Testing" in hard code, you have to use some value existed in the Data Table values.
That way your above code executes with no errors with no changes in databinding.

ASP C# Invalid attempt to call FieldCount when reader is closed

I have a function(PopulateStudents) that populates a dropdownlist with results from a database. This function is called on two different occasions: When a query string with id is provided, and in an onselectedindexchanged event. Basically, if an ID is provided from the URL, then get a database record of a student's ID, which contains semesterID and courseID. Then, all DDLs are populated based on the studentID.
If there is no ID in the URL, the user selects a semester from a DDL. Then the course DDL is populated based on the semester ID selected in the semester DDL. Then, the student DDL is populated based on the selected course.
The problem is that the PopulateStudent function works fine when no ID is provided in the query string and the user has to select the semester and then course. When the ID is provded in the query string, the PopulateStudents function does not work. The function throws an error that says Invalid attempt to call FieldCount when reader is closed. What is wrong with my code?
Here is the aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
GetStudentScores(Convert.ToInt32(Request.QueryString["id"]));
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetEnrolleeDetails", conn);
cmd.Parameters.Add("#enrollmentID", System.Data.SqlDbType.Int);
cmd.Parameters["#enrollmentID"].Value = Convert.ToInt32(Request.QueryString["id"]);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int semesterID = Convert.ToInt32(reader["semesterId"]);
int courseID = Convert.ToInt32(reader["courseId"]);
PopulateCourses(semesterID);
PopulateStudents(courseID);
DDSemester.SelectedValue = Convert.ToString(semesterID);
DDCourse.SelectedValue = Convert.ToString(courseID);
DDStudent.SelectedValue = Request.QueryString["ID"];
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
}
protected void DDCourse_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateStudents(Convert.ToInt32(DDCourse.SelectedValue));
}
}
protected void DDStudent_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
GetStudentScores(Convert.ToInt32(DDStudent.SelectedValue));
}
}
protected void DDSemester_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateCourses(Convert.ToInt32(DDSemester.SelectedValue));
}
}
private void PopulateCourses(int semesterID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetSemesterCourses", conn);
cmd.Parameters.Add("#semesterID", System.Data.SqlDbType.Int);
cmd.Parameters["#semesterID"].Value = semesterID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDCourse.DataSource = cmd.ExecuteReader();
DDCourse.DataTextField = "courseName";
DDCourse.DataValueField = "courseId";
DDCourse.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
private void PopulateStudents(int courseID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.CourseEnrollment", conn);
cmd.Parameters.Add("#courseId", System.Data.SqlDbType.Int);
cmd.Parameters["#courseId"].Value = courseID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDStudent.DataSource = cmd.ExecuteReader();
DDStudent.DataTextField = "fullName";
DDStudent.DataValueField = "enrollmentId";
this.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
Here is the asp:
<asp:Label ID="Label1" runat="server" Text="Semester:"></asp:Label>
<asp:DropDownList ID="DDSemester" runat="server" AutoPostBack="True" AppendDataBoundItems="true" DataSourceID="SqlDataSource1" DataTextField="semesterName" DataValueField="semesterId" OnSelectedIndexChanged="DDSemester_SelectedIndexChanged">
<asp:ListItem Text="Select a Semester"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label15" runat="server" Text="Course:"></asp:Label>
<asp:DropDownList ID="DDCourse" runat="server" AutoPostBack="True" AppendDataBoundItems="true" OnSelectedIndexChanged="DDCourse_SelectedIndexChanged">
<asp:ListItem Text="Select a Course"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label16" runat="server" Text="Student"></asp:Label>
<asp:DropDownList ID="DDStudent" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DDStudent_SelectedIndexChanged">
<asp:ListItem Text="Select a Student"></asp:ListItem>
</asp:DropDownList><br />
Thanks for your time.
There was actually one difference between the PopulateCourses and PopulateStudents functions that I didn't notice. In courses, I used DDCourse.DataBind() and in students I used this.DataBind().
In the populatestudents function, changing this.DataBind() to DDStudent.DataBind() fixed my problem.

fill dropdownlist from onselectindexchanged

im using asp.net and c#
im using 2 dropdownlist like dd1,dd2
how to fill 2nd dropdownlist dd2 by dd1 onselectindexchanged
my code is,
<asp:DropDownList ID="ddMedType" runat="server" CssClass="drop" AutoPostBack="true" OnSelectedIndexChanged="ddMedType_SelectedIndexChanged">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="Tablet">Tablet</asp:ListItem>
<asp:ListItem Value="Tonic">Tonic</asp:ListItem>
<asp:ListItem Value="Capsules">Capsules</asp:ListItem>
<asp:ListItem Value="DispoTab">Disposable Tablet</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddMedName" runat="server" CssClass="drop" >
<asp:ListItem Value="0">-Select-</asp:ListItem>
</asp:DropDownList>
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ddMedName.SelectedValue= reader["MedicineId"].ToString();
}
}
here the condition returns 2 items, but dropdownlist dd2 returns only 1 ...
You are setting the SelectedValue, this does not mean you're adding or removing items in your dropdownlist
DataTable medicines= new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'", con);
adapter.Fill(subjects);
ddMedName.DataSource = subjects;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddMedName.Items.Insert(0, new ListItem("-Select-", "0"));
You can also do it with the reader as follows:
ddMedName.Items.Clear();
ddMedName.Items.Add(new ListItem("-Select-", "0"));
while (reader.Read())
{
ddMedName.Items.Add(new ListItem(reader["MedicineName"].ToString(), reader["MedicineId"].ToString());
}
Try add item in the DropdownList..
DropDownList1.Items.Add(new ListItem(reader["MedicineId"].ToString(), reader["MedicineId"].ToString()));
Here is one solution may help you:
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
ddMedName.DataSource = reader;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}

SQL filled Droplist does not refresh values on postback

So here in my application I have 2 dropdowns, 4 labels and a gridview. The Medication Type drop list here with the text PO Meds is supposed to generate the number you see between the 2 drop lists, then based on that number, pull all of the records in the medications table with that number as an ID. The medications should populate in the dropdown marked Medication. The first time I run the application it pulls up the correct information but if I try changing that information, instead of the medication dropdown refilling with the new query information it just adds it to the medication droplist.
here are my 2 droplist and code:
HTML
<td>
<asp:DropDownList ID="ddlMedType" runat="server" DataSourceID="sdsMedType" DataTextField="MedType" DataValueField="MedType" AutoPostBack="True" OnSelectedIndexChanged="ddlMedType_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True">Select Medication Type</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedType" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer2 %>" SelectCommand="SELECT [num], [MedType] FROM [pharm_medication_Type]"></asp:SqlDataSource>
<asp:Label ID="lblMedType" runat="server" Visible="true"/>
</td>
<td>
<asp:DropDownList ID="ddlMedication" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="ddlMedication_SelectedIndexChanged" >
<asp:ListItem Selected="True">Choose A Medication</asp:ListItem>
</asp:DropDownList>
</td>
.CS
protected void ddlMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedType = ddlMedType.SelectedValue;
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
if (ddlMedType.SelectedValue != "Select Medication Type")
{
SqlCommand cmd1 = new SqlCommand("SELECT [num] from [pharm_medication_Type] where [MedType] = #MedType", conn1);
cmd1.Parameters.AddWithValue("#MedType", strMedType);
conn1.Open();
using (SqlDataReader reader2 = cmd1.ExecuteReader())
{
while (reader2.Read())
{
int strNum = reader2.GetInt32(0);
lblMedType.Text = Convert.ToString(strNum);
}
}
string strMedTypeID = lblMedType.Text;
SqlCommand cmd2 = new SqlCommand("Select [MedType_ID], [MedName] from [pharm_medications] where [MedType_ID] = #MedTypeID", conn1);
cmd2.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
ddlMedication.DataSource = cmd2.ExecuteReader();
lblMedType.Text = string.Empty;
ddlMedication.DataTextField = "MedName";
ddlMedication.DataValueField = "MedName";
ddlMedication.DataBind();
ddlMedType.DataBind();
lblMedType.DataBind();
}
}
}
protected void ddlMedication_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedTypeID = lblMedType.Text;
string strMedName = ddlMedication.SelectedValue;
if (ddlMedication.SelectedValue != "Choose A Medication")
{
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
SqlCommand cmd1 = new SqlCommand(#"SELECT DISTINCT [num], [MedType_ID], [MedName], [MedMin], [MedMax], [ChargingNumber]
FROM [pharm_medications] WHERE [MedType_ID] = #MedTypeID AND [MedName] = #MedName", conn1);
cmd1.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
cmd1.Parameters.AddWithValue("#MedName", strMedName);
conn1.Open();
using (SqlDataReader reader3 = cmd1.ExecuteReader())
{
while (reader3.Read())
{
int myNum = reader3.GetInt32(0);
int strMyMedTypeID = reader3.GetInt32(1);
string strMyMedName = reader3.GetString(2);
string strMedMin = reader3.GetString(3);
string strMedMax = reader3.GetString(4);
string strChargingNumber = reader3.GetString(5);
lblAutoMin.Text = strMedMin;
lblAutoMax.Text = strMedMax;
lblAutoChargeNum.Text = strChargingNumber;
}
}
}
}
}

show data in dropdownlist from sqlserver in asp.net using c#

I have three dropdownlist the code below
<asp:DropDownList ID="ForumTitleList" runat="server"
AutoPostBack="True">
</asp:DropDownList>
<asp:DropDownList ID="ForumSubTitleList" runat="server" AutoPostBack="True"
>
</asp:DropDownList>
<asp:DropDownList ID="ForumSubjectTitleList" runat="server" AutoPostBack="True"
>
</asp:DropDownList>
and the code behind is
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
namespace Auzine.Forums
{
public partial class ForumIT : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationFuntion();
DropForumTitle();
DropForumSubTitle();
DropForumSubjectTitle();
}
protected void DropForumTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//////////////////
}
}
protected void DropForumSubjectTitle()
{
if (Page.IsPostBack)
{
// ForumSubjectTitleList.Items.Clear();
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand com = new SqlCommand("select DISTINCT ForumSubjectTitle from ForumSubject where ForumSubTitlesID='" + ForumSubTitleList.SelectedValue.ToString() + "'", con);
SqlDataReader reader = com.ExecuteReader();
// ForumTitleList.Items.Clear();
while (reader.Read())
{
ForumSubjectTitleList.Items.Add(reader[0].ToString());
}
reader.Close();
con.Close();
}
}
protected void DropForumSubTitle()
{
if (Page.IsPostBack)
{
ForumSubTitleList.Items.Clear();
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumSubTitles from ForumSubtitle where ForumTitlesID='" + ForumTitleList.SelectedValue.ToString() + "' ";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumSubTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumSubTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumSubTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//////////////////
}
}
}
DropForumTitle() for dropdown1(ForumTitleList) list one is working fine and then for dropdown2(ForumSubTitleList) I want to search according to the selected value of dropdown1(ForumTitleList) and when do that as i write the code for dropdown1(ForumTitleList) then it is not showing any thing but when change the code from if (!Page.IsPostBack) to if (Page.IsPostBack) then it shows but the selected index goes aoutomatically to 0... It display right but when select any option from dropdown2(ForumSubTitleList) then it goes to selected index 0 bydefault and for this error the dropdown3(ForumSubjectTitleList) can recieve the selected item valu and does not shows subjectlist from database ... each of dropdown list are connected with an ID if dropdown displays any thing then second dropdown = to selected value of dropdown 1 and same as dropdown3 = to the selected valu of dropdown2
but I getting error with bothe dropdown2 and dropdown3
In short:
1-dropdown2 does not stay to the value I selected: let suppose in the LIst A, b, C, and D. when I click on A it posrback and the selected value is again A;
2- dropdown3 can not access the selected value of dropdown2 therefore it is not showing anything...
In every post-back you're doing two things with each drop-down list:
Re-populate it with data
Populate the next one
That first step is what's getting rid of your selected value. It can't retain the selected value when you clear the values and add new ones.
You need to separate these actions. For starters, let's assume you have DropDownList1 and its selection should drive DropDownList2. Then Page_Load should only be populating DropDownList1 and only when it's not a post-back. Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
PopulateDropDownList1();
}
To populate DropDownList2, you would respond to the SelectedIndexChanged event of DropDownList1. Something like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var value = DropDownList1.SelectedValue;
PopulateDropDownList2(value);
}
Keep in mind that Page_Load gets calls on every load of the page, even post-backs, and it's called before events like SelectedIndexChanged. So if you re-populate your parent list in Page_Load then there will no longer be a selected value in SelectedIndexChanged.
With the above scenario, the order of events would be:
User loads the page.
Page_Load executes.
It's not a post-back, so DropDownList1 gets populated with values.
User selects a value in DropDownList1 and triggers a post-back.
Page_Load executes.
It is a post-back, so Page_Load doesn't do anything.
DropDownList1_SelectedIndexChanged executes.
DropDownList2 gets populated with values.
At this point the user can now see what they selected in DropDownList1 and the new values in DropDownList2. Extending this to a third DropDownList is the same pattern. You'd create a DropDownList2_SelectedIndexChanged which does the same thing as DropDownList1_SelectedIndexChanged, but with the next cascading list.
Sample code to populate:
Method
private void Bind()
{
var dt = YourFunctionReturningDataTable();
//Assuming your table has two columns Id,Name
dropdownlist1.datasource = dt;
dropdownlist1.DataTextField = "Name";
dropdownlist1.DataValueField="Id";
dropdownlist1.DataBind();
dropdownlist1.Items.Insert(0, new ListItem("---Select---","-1"));
}
private void Page_Load()
{
if(!IsPostback)
{
Bind();
}
}
I think it is best way to show all genre name in dropdown list. I used EDMX and LINQ query.
ASPX:
===============
<asp:DropDownList ID="GenreList" runat="server" SelectMethod="GenreList_GetData" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
C#:
============
public IEnumerable<Genre> GenreList_GetData()
{
using(PlanetWroxEntities myEntities= new PlanetWroxEntities())
{
return (from genre in myEntities.Genres
orderby genre.SortOrder
select genre).ToList();
}
}

Categories

Resources