)GridView中使用DataKeyNames儲存資料索引值

來源:互聯網
上載者:User

GridView中DataKeyNames的應用小結
11:02:35]  
GridView的DataKeyNames屬性設為"ID,Name"

GridView1.DataKeyNames = new string[]{ "ID","Name" };

列中LinkButton的CommandName屬性設為"Delete"

就可以在GridView1_RowDeleting中寫代碼:

DataKey key = GridView1.DataKeys[e.RowIndex];
int id =
int.Parse(key[0].ToString());//得到id欄位值
string name =
key[1].ToString();//得到name欄位值

很多時候我們需要在GridView的RowCommand之類的事件中需要擷取當前行的一些關聯性的資料值。但這些資料值又沒有直接體現在GridView的列中。這個時候該怎麼辦呢?
有同學喜歡用隱藏列的方式,把需要使用但不顯示的欄位綁定到此列上,同時設定列寬為0或不顯示,使用時可以用常規的取某行某列的方式來擷取資料。
但是在Framework 2.0中,我們可以採用DataKeyNames的方式來擷取此類資料。

程式碼範例:
(前台)

        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Grup" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("GrupName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:ButtonField Text="按鈕" />
            </Columns>
        </asp:GridView>

Grup 為我們想使用但不需要顯示的列。(如果有多個欄位,使用逗號分開)
(後台)    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack )
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Grup");
            dt.Columns.Add("GrupName");

            dt.Rows.Add(new object[] { 0,"營業部" });
            dt.Rows.Add(new object[] { 1,"市場部" });

            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }

    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // 擷取當前行索引
        int index = Convert.ToInt32(e.CommandArgument);

        // 取出當前行資料索引值對象中的值
        string strGrup = ((GridView)sender).DataKeys[index].Values["Grup"].ToString(); 
    }

順便補充一句。
如果你使用模板列中放置按鈕控制項的方式,要想在按鈕事件中擷取這種欄位值就更簡單了。

只需要在按鈕的CommandArgument屬性設定為想綁定的欄位,如:

<asp:TemplateField>
     <ItemTemplate>
         <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" CommandArgument=' <%#Eval("Grup") %>' />
     </ItemTemplate>
</asp:TemplateField>

按鈕事件中如是寫:

protected void Button2_Click(object sender, EventArgs e)
{
    string strGrup = ((Button)sender).CommandArgument.ToString();
}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.