Gridview中的Request.QueryString

时间:2014-08-07 13:01:44

标签: c# gridview request.querystring

我的 GridView

中有 ImageButton 标签

网格定义如下

<asp:TemplateField HeaderText="Send kwm">
    <ItemTemplate>
        <center>
            <asp:ImageButton ID="Sendkwm" runat="server" ImageUrl="/Images/check.gif"
                OnClick="Sendkwm" />
        </center>
    </ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
    <ItemTemplate>
        <center>
            <asp:Label ID="kwm" runat="server" Text='<%# Eval("kwm").ToString() %>'></asp:Label>
        </center>
    </ItemTemplate>
</asp:TemplateField>

我的问题是我需要使用kwm的查询字符串值来更新我要显示的数据列。

我在网上搜索但似乎有必要使用GridView SqlDataSource,有没有替代方法来做这个替代方法?

我的代码隐藏

任何帮助将不胜感激,谢谢你。

protected void Sendkwm(object sender, EventArgs e)
{
    using (OdbcConnection conn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
    {
        sql = " UPDATE doTable " +
               " SET myDate = CURRENT_TIMESTAMP () " +
               " WHERE " +
               "    kwm =  //here the querystring value of kwm// ; ";

        using (OdbcCommand command =
            new OdbcCommand(sql,conn))
        {
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我只是使用代码隐藏,尤其是GridView&#39; s RowDataBound-event。这使得您的代码也更加健壮,因为您可以获得编译时安全性并且它的可读性/可维护性更高:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ImageButton sendKwm =  (ImageButton) e.Row.FindControl("Sendkwm ");
        Label lblKwm = (Label) e.Row.FindControl("kwm");
        lblKwm.Text = Request.QueryString["kwm"]; 
    }
}

现在,您可以通过以下方式获取ImageButton点击事件处理程序中的值:

protected void Sendkwm(object sender, EventArgs e)
{
    ImageButton sendKwm = (ImageButton)sender;
    GridViewRow row = (GridViewRow) sendKwm.NamingContainer;
    Label lblKwm = (Label)row.FindControl("kwm");

    using (OdbcConnection conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
    {
        string sql = @"UPDATE doTable 
                       SET myDate = CURRENT_TIMESTAMP()
                       WHERE kwm = @kwm;";

        using (OdbcCommand command = new OdbcCommand(sql, conn))
        {
            try
            {
                command.Parameters.AddWithValue("@kwm", lblKwm.Text);
                command.Connection.Open();
                command.ExecuteNonQuery();
            } catch (Exception ex)
            {
                throw ex;
            } finally
            {
                command.Connection.Close();
            }
        }
    }
}

另请注意,我已使用sql-parameters来阻止sql注入。