Insert double quotes when selected DropDownList is blank using C# and VB.Net in ASP.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

Hello Sir,

I want to insert a string like "" when i select blank from dropdownlist.

The dropdown list is shown below:

<div class="form-group">
    <label>
        Type</label>
    <asp:DropDownList ID="DropDownList2" class="form-control" runat="server">
        <asp:ListItem Value="0" Text="Blank">Blank</asp:ListItem>
        <asp:ListItem Value="1" Text="CANC">A</asp:ListItem>
        <asp:ListItem Value="2" Text="B">REPW</asp:ListItem>
        <asp:ListItem Value="3" Text="C">TRAN</asp:ListItem>
    </asp:DropDownList>
</div>

Thanks

You are viewing reply posted by: pandeyism 3 months ago.
Posted 3 months ago

Hi democloud,

Please refer below sample.

HTML

<label>
    Type</label>
<asp:DropDownList ID="DropDownList1" class="form-control" runat="server" OnSelectedIndexChanged="Insert"
    AutoPostBack="true">
    <asp:ListItem Value="0" Text="Blank">Blank</asp:ListItem>
    <asp:ListItem Value="1" Text="CANC">A</asp:ListItem>
    <asp:ListItem Value="2" Text="B">REPW</asp:ListItem>
    <asp:ListItem Value="3" Text="C">TRAN</asp:ListItem>
</asp:DropDownList>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient

Code

C#

protected void Insert(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("INSERT INTO TestDeom VALUES(@typeData)", con);
    if (DropDownList1.SelectedItem.Text == "Blank")
    {
        cmd.Parameters.AddWithValue("@typeData", "\"\"");
    }
    else
    {
        cmd.Parameters.AddWithValue("@typeData", DropDownList1.SelectedItem.Text);
    }
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

VB.Net

Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("INSERT INTO TestDeom VALUES(@typeData)", con)

    If DropDownList1.SelectedItem.Text = "Blank" Then
        cmd.Parameters.AddWithValue("@typeData", """""")
    Else
        cmd.Parameters.AddWithValue("@typeData", DropDownList1.SelectedItem.Text)
    End If

    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
End Sub