GridView. What is wrong with my code? Thank You.

S

shapper

Hello,

I need to loop though each row in a GridView and if the checkbox is a
Template Field is checked I want to display the value of an invisible
column named "LevelName".

I tried everything I could think off but I always get an error or no
value.
Could someone please let me know what might be wrong?

Here is my GridView init code:

1 Private Sub gvLevels_Init(ByVal sender As Object, ByVal e As
System.EventArgs) Handles gvLevels.Init
2
3 With gvLevels
4 .AutoGenerateColumns = False
5 .DataKeyNames = New String() {"LevelName"}
6 .DataSource = Levels_Fill()
7 .ID = "gvLevels"
8 End With
9
10 Dim bfLevelDescription As New BoundField
11 bfLevelDescription.DataField = "LevelDescription"
12 gvLevels.Columns.Add(bfLevelDescription)
13
14 Dim tfLevelSubscription As New TemplateField
15 tfLevelSubscription.ItemTemplate = New
tfLevelSubscription(ListItemType.Item)
16 gvLevels.Columns.Add(tfLevelSubscription)
17
18 gvLevels.DataBind()
19
20 End Sub ' gvLevels_Init

My grid view data source is:

1 Private Function Levels_Fill() As DataView
2
3 Dim dtLevels As New DataTable("Levels")
4 Dim dvLevels As DataView
5 dtLevels = Levels.GetAllLevels().Tables(0)
6 dtLevels.Columns.Add(New DataColumn("LevelSubscription",
GetType(Boolean)))
7
8 ' Define dtLevels primary key
9 dtLevels.PrimaryKey = New DataColumn()
{dtLevels.Columns("LevelName")}
10
11 dvLevels = New DataView(dtLevels, "", "LevelName",
DataViewRowState.CurrentRows)
12 Return dvLevels
13
14 End Function ' Levels_Fill

I am trying to access my check boxes as follows:

1 Dim dkLevel As DataKey
2 For Each gvrLevel As GridViewRow In gvLevels.Rows
3 Dim cbLevelSubscription As CheckBox =
CType(gvrLevel.FindControl("cbLevelSubscription"), CheckBox)
4 If cbLevelSubscription.Checked Then
5 dkLevel = gvLevels.DataKeys(gvrLevel.RowIndex)
6 Response.Write(dkLevel.Value)
7 End If
8 Next gvrLevel

When I click the button which will run the code that loops through
each check box I get the following error:

"Item has already been added.Key in dictionay: "LevelName" Key been
added: "LevelName"

I removed:

5 .DataKeyNames = New String() {"LevelName"}

And I stopped having this error but still does not work.

Any idea?

Thanks,

Miguel
 
R

Roland Dick

Hello Miguel,

Is it possible that your sub gvLevels_Init is being called several
times? (Maybe on each Page_Load without checking for a PostBack?)

If you remove setting the DataKeyNames property, then I don't think
gvLevels.DataKeys(gvrLevel.RowIndex) will return anything.

My advice would be: Set a breakpoint in the gvLevels_Init sub and make
sure it's only hit the first time the page loads, and "never" again
after that (and especially not when hitting the button that evaluates
the checkboxes!)

Hope this helps,

Cheers,

Roland
 
S

shapper

Hello Miguel,

Is it possible that your sub gvLevels_Init is being called several
times? (Maybe on each Page_Load without checking for a PostBack?)

If you remove setting the DataKeyNames property, then I don't think
gvLevels.DataKeys(gvrLevel.RowIndex) will return anything.

My advice would be: Set a breakpoint in the gvLevels_Init sub and make
sure it's only hit the first time the page loads, and "never" again
after that (and especially not when hitting the button that evaluates
the checkboxes!)

Hope this helps,

Cheers,

Roland

Hi Roland,

I did what you suggested and the code line .DataKeyNames = New
String() {"LevelName"} was running when page started and when the
button was clicked.
So I moved the code line to:

' gvLevels_Load
Private Sub gvLevels_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles gvLevels.Load

If Not Page.IsPostBack Then gvLevels.DataKeyNames = New String()
{"LevelName"}

End Sub ' gvLevels_Load

Inside the loop which goes through each GridView row I placed:

Response.Write(gvrLevel.RowIndex.ToString)

Response.Write(gvLevels.DataKeys(gvrLevel.RowIndex.ToString).Value.ToString())
****

Now I get an exception on code line ****:
System.ArgumentOutOfRangeException: Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index at System.Collections.ArrayList.get_Item(Int32 index) at
System.Web.UI.WebControls.DataKeyArray.get_Item(Int32 index) at ...

Any idea why?

Thanks,
Miguel
 
R

Roland Dick

Hi Miguel,

the following code works for me (it is C# as it is my preferred
language, but I'm sure you get the principles):

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GridView1.DataSource = GetDataSource();
this.GridView1.DataKeyNames = new string[] {
"LevelValue" };
this.GridView1.DataBind();
}
}

protected DataSet GetDataSource()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("LevelValue");
dt.Columns.Add("LevelText");
dt.Rows.Add(new object[] { 1, "One" });
dt.Rows.Add(new object[] { 2, "Two" });
dt.Rows.Add(new object[] { 3, "Three" });
return ds;
}

protected void Button1_Click(object sender, EventArgs e)
{
this.lblSelectedValues.Text = "";
foreach (GridViewRow row in this.GridView1.Rows)
{
CheckBox c = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (c.Checked)
{
DataKey dk =
this.GridView1.DataKeys[row.DataItemIndex];
if (dk != null)
this.lblSelectedValues.Text +=
dk.Value.ToString() + ", ";
}
}
}
}


And in the aspx:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LevelValue" Visible="False" />
<asp:BoundField DataField="LevelText" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
<br />
<asp:Label ID="lblSelectedValues" runat="server"
Text="Label"></asp:Label>


The field names are bit different to yours, but the logic should be the
same.

Hope this helps,

Roland
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top