Dropdown list not selecting value asp.net

2019-08-01 18:32发布

问题:

  ddlBanAcc.Items.Insert(0, new ListItem("", ""));
  string s = ddlBanAcc.SelectedValue;
  string[] words = s.Split('|');
  if (ddlBanAcc.SelectedIndex > 1)
  {
    query += "'and DtaLineAccountToDebit='" + words[0] + "'";
  }

On the ddlBankAcc (Dropdownlist selection) i am populating the Datagrid which is in the Update Panel

However the code is not executing and no value is getting selected by this statement ddlBanAcc.SelectedValue;

EDIT: HTML CODE

<td align="left" valign="top">
                            &nbsp;</td>
                 <td>
                            Bank Account:
                        </td>
                        <td>
 <asp:DropDownList runat="server" ID="ddlBanAcc" Width="160px" TaEvalex="3">
    </asp:DropDownList>

                        </td>

EDIT : how i am adding data in ddlBanAcc

DataTable dtbankaccount = oDBAccess.getDataTable("SELECT BkiAccountNb + ' | ' + BkiCurrency+ ' | ' +BkiAccountNb AS CONCATE  From VwCieBankAcc");
    ddlBanAcc.DataTextField = "CONCATE";
    ddlBanAcc.DataSource = dtbankaccount;

    ddlBanAcc.DataBind();

回答1:

You need to check IsPostBack, and if it is do not make DataBind, because this is making the DropDownList to re-get all his values, and lost the selection.

if(!IsPostBack)
    ddlBanAcc.DataBind();

Especial on DropDownList that is keep his values on ViewState you need to use the IsPostBack to the full process that is fill in. And the final code will be:

if(!IsPostBack)
{
    DataTable dtbankaccount = oDBAccess.getDataTable("SELECT BkiAccountNb + ' | ' + BkiCurrency+ ' | ' +BkiAccountNb AS CONCATE  From VwCieBankAcc");
    ddlBanAcc.DataTextField = "CONCATE";
    ddlBanAcc.DataSource = dtbankaccount;

    ddlBanAcc.DataBind();
}

If for any other reason you need to make DataBind and change the content of the DropDownList even after his selection you can always get the post back value using the Request.Form as:

Request.Form[DromDownListID.UniqueID]


回答2:

    <asp:DropDownList ID="ddlBanAcc" runat="server" DataTextField="" DataValueField="">
    </asp:DropDownList>

Try defining the DataTextField and DataValueField in the back end. This should help.



回答3:

You'll need to add AutoPostBack="true" to your DropDownList to get it to post back. I presume this is why the code is not executing.



回答4:

There is one more surprising issue that can cause this! My list values came from a database and the values had linefeed and carriage return: "\r\n". These values look like an innocent space, but actually they are not! My solution was to remove these hidden Char values. Hope it helps.