从列表视图中获取参数

时间:2013-06-13 08:06:57

标签: asp.net listview textbox

我有这段代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
        {
            System.Data.SqlClient.SqlCommand cmd;
            sc.Open();
            cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=@ID;", sc);
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1"); 

            cmd.ExecuteNonQuery();
            sc.Close();
            Response.Redirect("~/Zapasy_seznam.aspx");
        }
    }

我需要从listview获取值ID,但是使用此代码我有这个错误:

...expects the parameter '@ID', which was not supplied....

我的列表视图的这一部分......

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">       
                    <AlternatingItemTemplate>
                        <tr style="background-color: #e9ffe9;color: #284775;text-align:center">
                            <td>
                                <asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />

...

<td style="width:50px;background-color:white">
                                <asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
                                     <asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
                                </asp:LinkButton>
                            </td>                      
                        </tr>
                    </AlternatingItemTemplate>

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

根据评论,请尝试:

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)
{
    var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
    using (var sc = new SqlConnection(GetConnectionString()))
    {
        using (var cmd = sc.CreateCommand())
        {
            sc.Open();
            cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=@ID;";
            cmd.Parameters.AddWithValue("@ID", box1.Text);

            cmd.ExecuteNonQuery();
            sc.Close();
            Response.Redirect("~/Zapasy_seznam.aspx");
        }
    }
}

在此处使用数据感知控件(例如ListView)时,将使用每个数据项的自动唯一ID创建控件。这意味着您可以在页面中拥有多个相同的控件(例如本例中的“box1”),该控件应由((LinkButton)sender).Parent ListViewDataItem引用,代表行)。

ListViewDataItem.FindControl将在其自己的子范围内找到特定服务器ID的控件,允许您获取正在单击的按钮的同一行内的控件的值。