【问题标题】:show data in dropdownlist from sqlserver in asp.net using c#使用 c# 在 asp.net 中的 sql server 的下拉列表中显示数据
【发布时间】:2013-10-05 13:09:42
【问题描述】:

我在下面的代码中有三个下拉列表

  <asp:DropDownList ID="ForumTitleList" runat="server"

                        AutoPostBack="True">
                    </asp:DropDownList>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:DropDownList ID="ForumSubTitleList" runat="server" AutoPostBack="True"
                        >
                    </asp:DropDownList>
                    &nbsp;&nbsp;&nbsp;
                    <asp:DropDownList ID="ForumSubjectTitleList" runat="server" AutoPostBack="True"
                       >
                    </asp:DropDownList>

后面的代码是

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 工作正常,然后对于 dropdown2(ForumSubTitleList) 我想根据 dropdown1(ForumTitleList) 的选定值进行搜索,当我为 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从 dropdown2(ForumSubTitleList) 然后它默认进入选定的索引 0 并且对于这个错误 dropdown3(ForumSubjectTitleList) 可以接收选定的项目值并且不显示来自数据库的主题列表...如果下拉列表显示,每个下拉列表都与一个 ID 连接然后第二个下拉列表 = 下拉列表 1 的选定值,与下拉列表 3 = 下拉列表 2 的选定值相同

但是我在使用 dropdown2 和 dropdown3 时都遇到了错误

简而言之:

1-dropdown2 不会停留在我选择的值上:假设在 LIst A、b、C 和 D 中。当我点击 A 时,它会返回并且选择的值再次是 A;

2- dropdown3 无法访问 dropdown2 的选定值,因此它没有显示任何内容...

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    在每次回发中,您对每个下拉列表都做了两件事:

    1. 用数据重新填充它
    2. 填充下一个

    第一步是摆脱您选择的价值。当您清除值并添加新值时,它不能保留选定的值。

    您需要将这些操作分开。对于初学者,假设您有DropDownList1,它的选择应该驱动DropDownList2。那么Page_Load 应该只填充DropDownList1 并且仅当它不是回发时。像这样的:

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

    要填充DropDownList2,您将响应DropDownList1SelectedIndexChanged 事件。像这样的:

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var value = DropDownList1.SelectedValue;
        PopulateDropDownList2(value);
    }
    

    请记住,Page_Load 会在页面的每次 加载(甚至是回发)时获得调用,它被称为 before 事件,例如SelectedIndexChanged。因此,如果您在Page_Load 中重新填充父列表,那么SelectedIndexChanged 中将不再有选定值。

    在上述情况下,事件的顺序将是:

    1. 用户加载页面。
    2. Page_Load 执行。
    3. 这不是回发,因此DropDownList1 会填充值。
    4. 用户在DropDownList1 中选择一个值并触发回发。
    5. Page_Load 执行。
    6. 回发,所以Page_Load 没有做任何事情。
    7. DropDownList1_SelectedIndexChanged 执行。
    8. DropDownList2 填充了值。

    此时用户现在可以看到他们在DropDownList1 中选择的内容以及DropDownList2 中的新值。将此扩展到第三个DropDownList 是相同的模式。您将创建一个DropDownList2_SelectedIndexChanged,它与DropDownList1_SelectedIndexChanged 执行相同的操作,但具有下一个级联列表。

    【讨论】:

    • 感谢大卫爵士,但我仍然收到错误,一个错误是下拉菜单 2 再次选择了最高值,因此第三个无法正常进行
    • @SyedAzy:您能否更新您的问题以显示产生此行为的当前代码?如果列表的选择在回发时被重置,那么您可能仍在回发时重新填充列表。
    • 先生,非常感谢大家为我提供即时帮助....问题现在解决了,非常感谢,非常感谢,非常感谢,非常感谢:)
    【解决方案2】:

    要填充的示例代码:

    方法

    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();   
      }
    }
    

    【讨论】:

    • 谢谢阿米特·兰詹爵士,但我仍然收到错误,一个错误是下拉列表2再次选择了最高值,因此第三个无法继续进行
    • 先生,非常感谢大家为我提供即时帮助....问题现在解决了,非常感谢,非常感谢,非常感谢,非常感谢:)
    【解决方案3】:

    我认为在下拉列表中显示所有流派名称是最好的方法。我使用了 EDMX 和 LINQ 查询。

     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();
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多