从数据库的页面加载设置一个DropDownList值 [英] setting a dropdownlist value from database on page load

查看:192
本文介绍了从数据库的页面加载设置一个DropDownList值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来像是一件容易的工作,但还没有能够算起来out.I有,所有的用户数据从数据库中抽取到相应的文本框编辑个人资料页,标签等上Page_Load.The DropDownList的是如下绑定到一个表。我DDL是如下:

 < ASP:DropDownList的ID =ddlGender=服务器WIDTH =160像素的AutoPostBack =真OnDataBound =ddlGender_DataBound>
                        < / ASP:DropDownList的>

和被绑定如下:

 保护无效BindGenderDropDown()
{
    字符串CS = ConfigurationManager.ConnectionStrings [SportsActiveConnectionString]的ConnectionString。
    使用(SqlConnection的CON =新的SqlConnection(CS))
    {
        con.Open();
        CMD的SqlCommand =新的SqlCommand(选择tblGenders *,CON);
        SqlDataAdapter的大=新SqlDataAdapter的(CMD);
        DataSet的DS =新的DataSet();
        da.Fill(DS);
        ddlGender.DataSource = DS;
        ddlGender.DataTextField =GenderName;
        ddlGender.DataValueField =GenderId;
        ddlGender.DataBind();
    }
    ddlGender.Items.Insert(0,新的ListItem(---选择---,0));
    ddlGender.SelectedIndex = 0;
}

我不能够设置在DropDownList值though.Here是我做了什么:

 私人无效ExtractData由()
{
    字符串CS = ConfigurationManager.ConnectionStrings [fgff]的ConnectionString。
    使用(SqlConnection的CON =新的SqlConnection(CS))
    {
        con.Open();
        CMD的SqlCommand =新的SqlCommand(从tblRegPlayers1选择*其中userid ='PL00011',CON);
        SqlDataReader的RDR = cmd.ExecuteReader();
        而(rdr.Read())
        {
            字符串路径= RDR [ProfilePicPath]的ToString()。
            hfImagePath.Value = Path.GetFileName(路径);
            txtFName.Text = RDR [名字]的ToString()。
            txtLName.Text = RDR [姓氏]的ToString()。
            txtEmailAddress.Text = RDR [EmailAdd]的ToString()。
            txtContactNumber.Text = RDR [MobileNo]的ToString()。
            txtdob.Value = RDR [DOB]的ToString()。
            txtStreetAddress.Text = RDR [的StreetAddress]的ToString()。
            。txtZip code.Text = RDR [邮编code]的ToString();
           ddlGender.Items.FindByText(RDR [性别]的ToString())请选择= TRUE。
        }
    }

但它说'对象未设置为实例。于是我打了一下周围,试图做它在数据绑定是这样的:

 保护无效ddlGender_DataBound(对象发件人,EventArgs的发送)
{
    字符串CS = ConfigurationManager.ConnectionStrings [SportsActiveConnectionString]的ConnectionString。
    使用(SqlConnection的CON =新的SqlConnection(CS))
    {
        con.Open();
        CMD的SqlCommand =新的SqlCommand(从tblRegPlayers1选择*其中userid ='PL00011',CON);
        SqlDataReader的RDR = cmd.ExecuteReader();
        而(rdr.Read())
        {
            ddlGender.Items.FindByText(RDR [性别]的ToString())请选择= TRUE。
        }
    }

现在它不抛出任何错误,它不选择价值。

PS:1.I设置自动回真正的DDL。
2.我知道SQL注入攻击,并已进行了更改,使其看起来更简单。

我的最后pageLoad的是这样的:

 保护无效的Page_Load(对象发件人,EventArgs的发送)
{
    如果(!的IsPostBack)
    {
        //btnReset.Visible = FALSE;
        ExtractData由();
        BindDisabilityDropDown();
        BindGenderDropDown();
        BindStateDropDown();
    }
    如果(hfImagePath.Value ==|| hfImagePath.Value ==0)
    {
        imgCropped.ImageUrl =〜/ ProfilePictures / DefaultProfilePicture.png
        hfImagePath.Value =0;
    }
    其他
    {
        imgCropped.ImageUrl =〜/ ProfilePictures /+ hfImagePath.Value;
    }
    //lblRegistration.Text =会话[按钮]的ToString()。
}


解决方案

有关的,您呼叫 ExtractData由,你实际上已经绑定在的DropDownList BindGenderDropDown 方法。这意味着您的下拉列表将没有任何项目,当您尝试看看它,并设置选定的项目。首先第一件事情你需要移动数据绑定code以上 ExtractData由

二,你是你想在一个不寻常的方式来设置所选值。而不是尝试的 FindByText 你应该尝试设置的SelectedValue 来代替。

我假设 RDR的内容[性别] ExtractData由 GenderId 您已经绑定到下拉列表中,而不是在 GenderName 。我也假设 GenderId M ˚F GenderName (不过,如果你的实际执行情况稍微变化那么这是确定)。

尝试改变:

(RDR [性别]的ToString())

  ddlGender.Items.FindByText选择= TRUE。

要:

  ddlGender.SelectedValue = RDR [性别]的ToString()。

此外,一定要删除已添加了数据绑定处理程序中的code,这是没有必要在这里。

Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :

   <asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
                        </asp:DropDownList>

and is binded as below :

protected void BindGenderDropDown()
{
    string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        ddlGender.DataSource = ds;
        ddlGender.DataTextField = "GenderName";
        ddlGender.DataValueField = "GenderId";
        ddlGender.DataBind();
    }
    ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
    ddlGender.SelectedIndex = 0;
}

I am not able to set a value in the dropdownlist though.Here is what I have done :

 private void ExtractData()
{
    string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            string path = rdr["ProfilePicPath"].ToString();
            hfImagePath.Value = Path.GetFileName(path);
            txtFName.Text = rdr["FirstName"].ToString();
            txtLName.Text = rdr["LastName"].ToString();
            txtEmailAddress.Text = rdr["EmailAdd"].ToString();
            txtContactNumber.Text = rdr["MobileNo"].ToString();
            txtdob.Value = rdr["DOB"].ToString();
            txtStreetAddress.Text = rdr["StreetAddress"].ToString();
            txtZipCode.Text = rdr["ZipCode"].ToString();
           ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
        }
    }

But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :

    protected void ddlGender_DataBound(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
        }
    }

Now it doesnt throw any error and it doesnt select the value as well.

PS : 1.I have set Autopostback true for the ddl. 2.I am aware of sqlInjection and have made changes to make it look simpler.

My final PageLoad looks like this :

    protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //btnReset.Visible = false;
        ExtractData();
        BindDisabilityDropDown();
        BindGenderDropDown();
        BindStateDropDown();
    }
    if (hfImagePath.Value == "" || hfImagePath.Value == "0")
    {
        imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
        hfImagePath.Value = "0";
    }
    else
    {
        imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
    }
    //lblRegistration.Text = Session["Button"].ToString();
}

解决方案

For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.

Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.

I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).

Try changing:

ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;

To:

ddlGender.SelectedValue = rdr["Gender"].ToString();

Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.

这篇关于从数据库的页面加载设置一个DropDownList值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆