简体   繁体   English

ASP。 Net (C#) GridView 按钮控制内部触发 Gridview

[英]ASP. Net (C#) GridView Buttons Control Triggering Inside Gridview

I have managed to add buttons in all my rows of gridview. But I am having problem with triggering controls while clicking on each button.我已经设法在 gridview 的所有行中添加按钮。但是我在单击每个按钮时遇到触发控件的问题。 What I want to do is, I want to display some contents of the row of which the button is clicked in the gridview. Below is my.aspx code.我想做的是,我想显示gridview中点击按钮的行的一些内容。下面是我的.aspx代码。 Please tell me how to write CS to perform this particular function.请告诉我如何编写 CS 来执行这个特定的 function。

<asp:GridView ID ="GridView1" class="table table-bordered table-condensed table-responsive table-hover" CellPadding="3" BorderWidth="7px" AllowPaging="True"  PagerStyle-HorizontalAlign="Left" PageSize="5" HeaderStyle-Font-Bold="True" PagerStyle-CssClass="GridPager" HeaderStyle-ForeColor="WhiteSmoke" HeaderStyle-BackColor="#0099cc" AllowSorting="True" AutoGenerateColumns="true" runat="server" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCommand="GridView_RowCommand">
                      <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
               <asp:Button ID="btnGenNew" runat="server" CommandName="GJobID" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="View" CssClass="btn btn-info" Enabled="true" /> 
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
                </asp:GridView>

You really don't need to use command arugment, or in fact bother using the GV events.您真的不需要使用命令参数,或者实际上不必费心使用 GV 事件。

Just drop in the button as you have.只需按原样放入按钮即可。 And NOTE VERY careful, do use the datakeys feature.并注意非常小心,请使用数据键功能。 This allows you to get the database PK row id, but NOT have to put that value in the markup, or display it, or even hide it.这允许您获取数据库 PK 行 ID,但不必将该值放在标记中,或显示它,甚至隐藏它。

So, lets do a simple GV, and use the above knowledge.所以,让我们做一个简单的 GV,并使用上面的知识。

Now, I going to include some "cells" or databound columns, and then some template columns.现在,我将包括一些“单元格”或数据绑定列,然后是一些模板列。

And we will drop in two PLANE JANE buttons - and we will use PLANE jane good old standard server click events.我们将放入两个 PLANE JANE 按钮 - 我们将使用 PLANE jane 良好的旧标准服务器点击事件。 No messing with command name or some such.不要弄乱命令名称或类似的名称。

Ok, so here is our markup:好的,这是我们的标记:

        <asp:GridView ID="GHotels" runat="server" CssClass="table"
             AutoGenerateColumns="False" DataKeyNames="ID" >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
                <asp:BoundField DataField="LastName" HeaderText="LastName"       />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
                <asp:BoundField DataField="City" HeaderText="City"               />
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:TextBox ID="txtDescription" runat="server"
                            TextMode="MultiLine" Rows="4" Columns="40"
                            Text='<%# Eval("Description") %>'  >
                        </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Tog City">
                    <ItemTemplate>
                        <asp:Button ID="btnToggleCity" runat="server" Text="Tog City" 
                            CssClass="btn"/>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Tog Hotel">
                    <ItemTemplate>
                        <asp:Button ID="btnTogHotel" runat="server" Text="Tog Hotel" 
                            CssClass="btn"/>
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
        </asp:GridView>

And our code to load:以及我们要加载的代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";

            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GHotels.DataSource = rstData;
                GHotels.DataBind();
            }
        }
    }

And we now have this:我们现在有这个:

在此处输入图像描述

So, lets wire up the first button (toggle the City column).因此,让我们连接第一个按钮(切换城市列)。

So, lets add a plane jane click event.所以,让我们添加一个平面简点击事件。 You can't double click on a button (like normal since it inside of the grid), so use markup, and go like this:你不能双击一个按钮(因为它在网格内部所以正常),所以使用标记,和 go 像这样:

在此处输入图像描述

So, for the button, type in OnClick=, and NOTE HOW intel-sense pops up and gives you the option to create a click event.因此,对于按钮,键入 OnClick=,然后注意如何弹出 intel-sense 并为您提供创建点击事件的选项。

The markup will become this:标记将变成这样:

<asp:TemplateField HeaderText="Tog City">
  <ItemTemplate>
    <asp:Button ID="btnToggleCity" runat="server" Text="Tog City" 
       CssClass="btn" OnClick="btnToggleCity_Click"  />
  </ItemTemplate>

</asp:TemplateField> </asp:模板字段>

So, now flip to code behind, and we can do this:所以,现在转到代码隐藏,我们可以这样做:

    protected void btnToggleCity_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow gRow = btn.NamingContainer as GridViewRow;

        // get row index
        Debug.Print("Row index clicked on = " + gRow.RowIndex);

        // get data base PK id (data keys setting)

        int? PKID = GHotels.DataKeys[gRow.RowIndex]["ID"] as int?;
        Debug.Print("data PK id = " + PKID);

        // Now show hide say the City column.
        // this is a NON template, so we use cells collection.

        if (gRow.Cells[3].BackColor == System.Drawing.Color.FromName("skyblue"))
            gRow.Cells[3].BackColor = System.Drawing.Color.FromName("white");
        else
            gRow.Cells[3].BackColor = System.Drawing.Color.FromName("skyblue");


    }

So, the above operates on the current row.所以,上面的操作是在当前行上进行的。

We can "toggle" the color of the city cell.我们可以“切换”城市单元格的颜色。 You get this:你得到这个:

在此处输入图像描述

And even wtih post-backs, the color does persist (so each row, we can toggle blue on and then off).即使有回发,颜色也会持续存在(所以每一行,我们都可以打开然后关闭蓝色)。

Ok, for the next button, we do the same, but this time, we going to use a template field.好的,对于下一个按钮,我们做同样的事情,但是这次,我们将使用模板字段。

So, rule is:所以,规则是:

 databound column - use cells() - and by index - not name

 template columns - use find control,

So, for the 2nd button, we add the OnClick (let intel-sense offer to create event).因此,对于第二个按钮,我们添加 OnClick(让智能感知提供创建事件)。

And then in our code behind, we get this:然后在我们后面的代码中,我们得到这个:

    protected void btnTogHotel_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow gRow = btn.NamingContainer as GridViewRow;

        // get row index
        Debug.Print("Row index clicked on = " + gRow.RowIndex);

        // get data base PK id (data keys setting)

        int? PKID = GHotels.DataKeys[gRow.RowIndex]["ID"] as int?;
        Debug.Print("data PK id = " + PKID);

        // Now toggle color for description

        TextBox txtD = gRow.FindControl("txtDescription") as TextBox;

        txtD.Visible = !txtD.Visible;
    }

So say I click on the last 3 buttons (tog hotel - I meant to type "description")所以说我点击最后 3 个按钮(tog hotel - 我的意思是输入“描述”)

So, we now see this:所以,我们现在看到这个:

在此处输入图像描述

So, even with a plane jane button click:所以,即使有一个飞机简按钮点击:

We can get the row index

We can get the database PK id (and note how not displayed in markup)

We can get a cell, or a templated control - do whatever we want then.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM