【发布时间】:2019-11-19 02:05:33
【问题描述】:
我的逻辑是,如果 ddlCoffee.SelectedIndex = 0 它不会在我的数据库中添加任何行。我确实尝试过 sqlcmd.Parameters.AddWithValue("@Qty", ((object)ddlCoffee.SelectedIndex) ?? DBNull.Value); 但在 SQL 中它显示为 Qty 0我不想要的 SQL 数据库中的 strong> 值行。如果 Qty 为 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>
【问题讨论】:
-
我认为如果您选择不同的下拉项目,您可以检查插入的值,如果您可以按照我的回答进行操作
标签: c# asp.net webforms dropdown listitem