Как заполнить DropDownList из базы данных в asp.net? - PullRequest
3 голосов
/ 08 января 2011

как заполнить DropDownList из базы данных в asp.net?

и когда я выбираю значение из DropDownList, как перехватить это событие?

Conn.Open();
SQL = "SELECT distinct city FROM MEN";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();

DropDownList1. ?????? (what do to ?)

спасибо заранее

Ответы [ 6 ]

5 голосов
/ 08 января 2011

Вы устанавливаете DataSource, DataTextField и DataValueField и вызываете DataBind() для заполнения выпадающий список.

Источник данных может быть в значительной степени любым IEnumerable, и текст и значение будут найдены с отражением.

Событие, которое вы хотите перехватить, - это событие SelectedIndexChanged - оно срабатывает при изменении выбора.

2 голосов
/ 30 мая 2012

Сначала возьмите детали в наборе данных, затем вам поможет следующий код:

DropDownList1.DataSource = ds
DropDownList1.DataTextField = "emailid"
DropDownList1.DataValueField = "userid"
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, New ListItem("select", "-1"))
1 голос
/ 31 января 2012

Простой пример кода:

DropDownList.DataSource = yourDataSource;
DropDownList.DataTextField = "displayNameColumnName ";
DropDownList.DataValueField = "TheValueColumnName";
DropDownList.DataBind();
0 голосов
/ 31 августа 2016

Другой способ привязки выпадающего списка - это ...

<asp:DropDownList ID="ddlCity" runat="server" DataValueField="pkId" DataTextField="cityName" DataSourceID="sqlDB">
    </asp:DropDownList>
    <asp:SqlDataSource ID="sqlDB" ConnectionString='$Name of connecitonstring' runat="server" SelectCommand="Select * from tbl_City"></asp:SqlDataSource>
0 голосов
/ 21 апреля 2015
//...Wrote separate class for calling this function
FunctionClass obj = new FunctionClass();
List<Designation> details = new List<Designation>();
bool result1 = obj.DataDrop(out details);
if (result1 == true)
{
dropDownDesignation.DataSource = details;
dropDownDesignation.DataTextField = "designation";
dropDownDesignation.DataValueField = "Designation_ID";
dropDownDesignation.DataBind();
dropDownDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
}

//..This function wrote inside FunctionClass and called from aspx.cs page
public bool DataDrop(out List<Designation> designationDetails)
{
designationDetails = new List<Designation>();
conn = new SqlConnection(connectionName);
conn.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DesignationDetails";
userReader = command.ExecuteReader();
if(userReader.HasRows)
{
    while(userReader.Read())
{
    designationDetails.Add(new Designation()
    {
            designationId=userReader.GetInt32(0),
            designation=userReader.GetString(1)
        });
 }
}
return true;
}
//..This should declare outside the class but inside the namespace
public class Designation
{
public int designationId { get; set; }
public string designation { get; set; }
}
0 голосов
/ 31 января 2012

Это может быть полное прохождение для вас в этом случае:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDropDownLists();
    }
}

protected void Page_Init(object sender, EventArgs e)
{ 

        SqlDataSource sqlDS = new SqlDataSource();
        sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
        sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
        form1.Controls.Add(sqlDS);

        DropDownList ddl = new DropDownList();
        ddl.ID = "dddlGender";
        ddl.DataSource = sqlDS;
        ddl.DataTextField = "Gender";
        ddl.DataValueField = "GenderID";
        form1.Controls.Add(ddl);

        // ... Repeat above code 9 times or put in a for loop if they're all the same...
}

private void BindDropDownLists()
{
    foreach (Control ctl in form1.Controls)
    {
        if (ctl is DropDownList)
        {
            (ctl as DropDownList).DataBind();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...