我的逻辑是,如果ddlCoffee.SelectedIndex = 0,则不会在我的数据库中添加任何行。我确实尝试过 sqlcmd.Parameters.AddWithValue(“ @ Qty”,((object)ddlCoffee.SelectedIndex)?? DBNull.Value); ,但是在SQL中它以 Qty 0 出现。我不想要的SQL数据库中的strong>值行。如果数量为0,我不想添加任何行。请告知我该怎么办?
.aspx.cs
protected void BtnSubmit_Click(object sender,EventArgs e)
{
string connString = "Data Source";
string insertCommand = "INSERT INTO tbDrinks ( DrinkName,DateOfOrder,Qty,username,UserCompany) " +
"values(@DrinkName,@DateOfOrder,@Qty,@username,@UserCompany)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCommand,conn))
{
sqlcmd.Parameters.AddWithValue("@DrinkName",lblCoffee.Text);
sqlcmd.Parameters.AddWithValue("@DateOfOrder",DateTime.Today);
if (ddlCoffee.SelectedIndex != 0)
{
sqlcmd.Parameters.AddWithValue("@Qty",ddlCoffee.SelectedValue);
}
else
{
//sqlcmd.Parameters.AddWithValue("@Qty",((object)ddlCoffee.SelectedIndex) ?? DBNull.Value);
//Will Not Add in SQL Database
}
sqlcmd.Parameters.AddWithValue("@username",txtusername.Text);
sqlcmd.Parameters.AddWithValue("@UserCompany",txtCompanyName.Text);
sqlcmd.ExecuteNonQuery();
}
}
}
.aspx
<table id="tbHotDrinks" class="auto-style3" border="1" bordercolor="#1FC3F3" runat="server">
<tr>
<td>
<asp:Label ID="lblCoffee" runat="server" Text="Coffee"></asp:Label>
</td>
<td class="auto-style2">
<asp:Image ID="coffee" runat="server" Height="76px" ImageUrl="~/images/coffee.gif" Width="99px" ImageAlign="TextTop" />
</td>
<td class="auto-style11">
<asp:DropDownList ID="ddlCoffee" runat="server">
<asp:ListItem Value="0">--Select Qty--</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>