DataKeyNames,DataKeys 用法

來源:互聯網
上載者:User

DataKeyNames作為GridView中的一個屬性,我們可以利用這個屬性結合DataKeys方便的訪問GridView中每個欄位的值。

先說怎麼用

DataKeyNames可以直接在GridView屬性中設定,多個欄位之間用逗號分隔,如:Id,Name,Sex 。

在用代碼綁定GridView時,也可以設定DataKeyNames:

1 gv.DataSource = Bind();
2
3 gv.DataKeyNames =newstring[]
4 {
5   "Id","Name","Sex"
6 };
7
8 gv.DataBind();複製代碼

DataKeyNames設定好以後,就可以用DataKeys來訪問DataKeyNames中每個欄位的值了,假如寫在RowDeleting事件中

1 protectedvoid gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
2 {
3   string id = gv.DataKeys[e.RowIndex].Value.ToString();//對象中索引0位置的對象值
4 }複製代碼

這樣寫也是對的:

1 string id = gv.DataKeys[e.RowIndex].Values["Id"].ToString();

按照索引同樣可以取:

1 string id = gv.DataKeys[e.RowIndex][0].ToString();//取Id
2 string name= gv.DataKeys[e.RowIndex][1].ToString();//取Name
3 string sex = gv.DataKeys[e.RowIndex][2].ToString();//取Sex複製代碼

可以這樣用的原因:

當你設定了DataKeyNames屬性,它儲存了指定資料庫中想要擷取值的列名,該屬性會自動填滿到GridView控制項的DataKeys集合

分類: ASP.NET標籤: DataKeyNames, DataKeys綠色通道:好文要頂關注我收藏該文與我聯絡 Amos Von
關注 - 0
粉絲 - 0  +加關注00 (請您對文章做出評價)  

DataKeyNames作為GridView中的一個屬性,我們可以利用這個屬性結合DataKeys方便的訪問GridView中每個欄位的值。

先說怎麼用

DataKeyNames可以直接在GridView屬性中設定,多個欄位之間用逗號分隔,如:Id,Name,Sex 。

在用代碼綁定GridView時,也可以設定DataKeyNames:

1 gv.DataSource = Bind();
2
3 gv.DataKeyNames =newstring[]
4 {
5   "Id","Name","Sex"
6 };
7
8 gv.DataBind();複製代碼

DataKeyNames設定好以後,就可以用DataKeys來訪問DataKeyNames中每個欄位的值了,假如寫在RowDeleting事件中

1 protectedvoid gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
2 {
3   string id = gv.DataKeys[e.RowIndex].Value.ToString();//對象中索引0位置的對象值
4 }複製代碼

這樣寫也是對的:

1 string id = gv.DataKeys[e.RowIndex].Values["Id"].ToString();

按照索引同樣可以取:

1 string id = gv.DataKeys[e.RowIndex][0].ToString();//取Id
2 string name= gv.DataKeys[e.RowIndex][1].ToString();//取Name
3 string sex = gv.DataKeys[e.RowIndex][2].ToString();//取Sex複製代碼

可以這樣用的原因:

當你設定了DataKeyNames屬性,它儲存了指定資料庫中想要擷取值的列名,該屬性會自動填滿到GridView控制項的DataKeys集合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.