Foreach声明

时间:2015-09-28 13:55:26

标签: c# asp.net

我想从listview插入多行数据到数据库

我遇到错误说明:

  

从对象类型System.Web.UI.WebControls.Literal到已知的托管提供程序本机类型不存在映射。

我有这个aspx

<asp:ListView ID="lvPODetails" runat="server">
    <ItemTemplate>
        <tr>
            <td>
                <asp:Literal ID="ltRefNo" runat="server" Text='<%# Eval("PODetailNo") %>' Visible="false" />
                <%# Eval("ProductName")%>
            </td>
            <td>
                <%# Eval("Price", "{0: #,###.00}") %>
            </td>
            <td><%# Eval("DesiredQuantity") %></td>
            <td><asp:TextBox ID="txtQuantity" runat="server" type="number" Text='<%# Eval("DesiredQuantity") %>' class="form-control" /></td>
            <td><%# Eval("POAmount", "{0: #,###.00}") %></td>
            <td><%# Eval("POAmount", "{0: #,###.00}") %></td>
            <td>

            </td>
        </tr>

    </ItemTemplate>
    <EmptyDataTemplate>
        <tr>
            <td colspan="4"><h2 class="text-center">No records found.</h2></td>
        </tr>
    </EmptyDataTemplate>
</asp:ListView>

这是插入

的.cs
 protected void btnAdd_Click(object sender, EventArgs e)
{

    foreach (ListViewItem item in lvPODetails.Items)
    {
        TextBox quantity = (TextBox)item.FindControl("txtQuantity");
        Literal ltr = (Literal)item.FindControl("ltRefNo");


        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO Inventory VALUES (@ProductID, @Quantity)";
        cmd.Parameters.AddWithValue("@ProductID", ltr);
        cmd.Parameters.AddWithValue("@Quantity", quantity);
        cmd.ExecuteNonQuery();
        con.Close();

    }

}

我认为foreach循环是错误的,但我不能说它有什么问题。

2 个答案:

答案 0 :(得分:2)

<强> ltr.Text

 protected void btnAdd_Click(object sender, EventArgs e)
{

    foreach (ListViewItem item in lvPODetails.Items)
    {
        TextBox quantity = (TextBox)item.FindControl("txtQuantity");
        Literal ltr = (Literal)item.FindControl("ltRefNo");


        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO Inventory VALUES (@ProductID, @Quantity)";
        cmd.Parameters.AddWithValue("@ProductID", ltr.Text);
        cmd.Parameters.AddWithValue("@Quantity", quantity.Text);
        cmd.ExecuteNonQuery();
        con.Close();

    }

}

希望你的问题得到解决。

答案 1 :(得分:1)

您应该将.Text用于Literal和TextBox:

cmd.Parameters.AddWithValue("@ProductID", ltr.Text);
cmd.Parameters.AddWithValue("@Quantity", quantity.Text);

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.literal.text(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.text(v=vs.110).aspx