Marius Vasile

Marius Vasile

  • 552
  • 1.9k
  • 145.8k

SelectedItem.Text null when postback

Jun 16 2024 5:31 PM

I have a DropdownList

<asp:DropDownList ID="ddlComponentaActivitate" class="form-control form-control-sm" Style="background-color: #FFFFE0; font-size: 12px;" runat="server" AutoPostBack="True"
    OnSelectedIndexChanged="ddlComponentaActivitate_SelectedIndexChanged" ClientIDMode="Static">
    <asp:ListItem Enabled="true" Text="Componenta sistemului de munca" Value="-1"></asp:ListItem>
    <asp:ListItem Value="1" Text="Executant"></asp:ListItem>
    <asp:ListItem Value="3" Text="Sarcina de munca"></asp:ListItem>
    <asp:ListItem Value="2" Text="Mijloace de productie"></asp:ListItem>
</asp:DropDownList>

Based on the selected text I populate another ddl with

protected void ddlComponentaActivitate_SelectedIndexChanged(Object sender, EventArgs e)
{
    ddlFactorRisc.Items.Clear();
    ddlFactorRisc.Items.Add("Factor de risc");
    using (SqlConnection conn = new SqlConnection(connString))
    {
        string sqlQuery = "SELECT FactorRisc, FRFID FROM tblFactoriRiscFactori WHERE FRCID = @FRCID ORDER BY FactorRisc";
        using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@FRCID", ddlComponentaActivitate.SelectedItem.Value);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            conn.Open();
            DataSet ds = new DataSet();
            da.Fill(ds);
            ddlFactorRisc.DataSource = ds.Tables[0];
            ddlFactorRisc.DataBind();
            conn.Close();
        }
    }
    ActiveTAB.Value = "#TabEvaluare";
}

The second ddl on View with

<asp:DropDownList ID="ddlFactorRisc" class="form-control form-control-sm" Style="background-color: #FFFFE0; font-size: 12px;" runat="server" AutoPostBack="False"
    DataTextField="FactorRisc" DataValueField="FRFID" AppendDataBoundItems="true" ClientIDMode="Static">
</asp:DropDownList>

But when I try to add data to table using FactorRisc as parameter

cmd.Parameters.AddWithValue("@FactorRisc", ddlFactorRisc.SelectedItem.Text);

I have error that say cannot add null. So it seems it will not get the value. Worth to mention I have 2 more ddl on page, one listed below

<asp:DropDownList ID="ddlGravitate" class="form-control form-control-sm" Style="background-color: #FFFFE0; font-size: 12px;" runat="server" AutoPostBack="False"
    DataTextField="Gravitate" DataValueField="ClsGravitate" AppendDataBoundItems="true" ClientIDMode="Static">
</asp:DropDownList>

On screen data is visible but error on postback. Why?


Answers (1)