- PR -

GridViewのRowCreated時にキー情報(DataKeyNamesの値)を取得したい

1
投稿者投稿内容
未記入
ベテラン
会議室デビュー日: 2008/01/15
投稿数: 65
投稿日時: 2008-05-29 17:54
GridViewの行をクリックした時(onClick)に新しいウインドウを開く(行のキーをパラメタとして渡す)
ようにしたいので、RowCreatedイベントで当該レコードのキー情報を取得したいのですが可能でしょうか?
キー情報はRecIDに入っていて、GridViewのDataKeyNamesにはRecIDを指定しています。

やり方がわからなかったのでRecIDの列を設けTemplateFieldに変換し
<パターン1>
Dim addButton As Label = CType(e.Row.Cells(1).Controls(0), Label)
RecID = addButton.Text

<パターン2>
RecID = e.Row.Cells(1).Text
ということもやってみましたがダメでした。

パターン1では変換できないというエラーが発生し、パターン2では値が入っていませんでした。
これはRowCreatedで実行しているのが原因のような気もしますが、onClickにコードを書き込む都合上
RowCreatedでキーを取得する必要があるのかなと思っています。

よろしくお願いします。

【GridViewの定義】
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RecID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField HeaderText="RecID" InsertVisible="False" SortExpression="RecID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("RecID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("RecID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
未記入
ベテラン
会議室デビュー日: 2008/01/15
投稿数: 65
投稿日時: 2008-05-29 20:33
処理をRowDataBoundイベントに移し、
Dim RecIDLabel As Label = CType(e.Row.Cells(1).FindControl("Label1"), Label)
RecID = RecIDLabel.Text
とやることで値を取得できました。
Controls(0)はLabel1だと思っていたのですが違うようですね。
FindControlを使うのか、Controlsを使うのかは何を基準に判断すればいいのでしょうか?

また、DataKeyNamesのキー情報はこの方法でないと取得できないのでしょうか?
べる
ぬし
会議室デビュー日: 2003/09/20
投稿数: 1093
投稿日時: 2008-05-29 21:28
RowCreatedで
GridView1.DataKeys[e.Row.DataItemIndex].Value
で取得できませんか?(複合キーの場合はValuesで複数とれるみたい)

#e.Row.RowType判定は忘れずに
未記入
ベテラン
会議室デビュー日: 2008/01/15
投稿数: 65
投稿日時: 2008-05-30 09:50
引用:

べるさんの書き込み (2008-05-29 21:28) より:
RowCreatedで
GridView1.DataKeys[e.Row.DataItemIndex].Value
で取得できませんか?(複合キーの場合はValuesで複数とれるみたい)

#e.Row.RowType判定は忘れずに



次の3通りの方法で取得できました。

RecID = CType(GridView1.DataKeys(e.Row.DataItemIndex).Value, String)
RecID1 = CType(GridView1.DataKeys(e.Row.RowIndex).Value, String)
RecID2 = CType(GridView1.DataKeys(e.Row.RowIndex).Values("RecID"), String)

ありがとうございました。
1

スキルアップ/キャリアアップ(JOB@IT)