473,770 Members | 1,989 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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(B yVal sender As Object, ByVal e As
System.EventArg s) Handles gvLevels.Init
2
3 With gvLevels
4 .AutoGenerateCo lumns = False
5 .DataKeyNames = New String() {"LevelName" }
6 .DataSource = Levels_Fill()
7 .ID = "gvLevels"
8 End With
9
10 Dim bfLevelDescript ion As New BoundField
11 bfLevelDescript ion.DataField = "LevelDescripti on"
12 gvLevels.Column s.Add(bfLevelDe scription)
13
14 Dim tfLevelSubscrip tion As New TemplateField
15 tfLevelSubscrip tion.ItemTempla te = New
tfLevelSubscrip tion(ListItemTy pe.Item)
16 gvLevels.Column s.Add(tfLevelSu bscription)
17
18 gvLevels.DataBi nd()
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("Leve ls")
4 Dim dvLevels As DataView
5 dtLevels = Levels.GetAllLe vels().Tables(0 )
6 dtLevels.Column s.Add(New DataColumn("Lev elSubscription" ,
GetType(Boolean )))
7
8 ' Define dtLevels primary key
9 dtLevels.Primar yKey = New DataColumn()
{dtLevels.Colum ns("LevelName") }
10
11 dvLevels = New DataView(dtLeve ls, "", "LevelName" ,
DataViewRowStat e.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 cbLevelSubscrip tion As CheckBox =
CType(gvrLevel. FindControl("cb LevelSubscripti on"), CheckBox)
4 If cbLevelSubscrip tion.Checked Then
5 dkLevel = gvLevels.DataKe ys(gvrLevel.Row Index)
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

Mar 13 '07 #1
3 4075
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.DataKe ys(gvrLevel.Row Index) 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

shapper schrieb:
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(B yVal sender As Object, ByVal e As
System.EventArg s) Handles gvLevels.Init
2
3 With gvLevels
4 .AutoGenerateCo lumns = False
5 .DataKeyNames = New String() {"LevelName" }
6 .DataSource = Levels_Fill()
7 .ID = "gvLevels"
8 End With
9
10 Dim bfLevelDescript ion As New BoundField
11 bfLevelDescript ion.DataField = "LevelDescripti on"
12 gvLevels.Column s.Add(bfLevelDe scription)
13
14 Dim tfLevelSubscrip tion As New TemplateField
15 tfLevelSubscrip tion.ItemTempla te = New
tfLevelSubscrip tion(ListItemTy pe.Item)
16 gvLevels.Column s.Add(tfLevelSu bscription)
17
18 gvLevels.DataBi nd()
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("Leve ls")
4 Dim dvLevels As DataView
5 dtLevels = Levels.GetAllLe vels().Tables(0 )
6 dtLevels.Column s.Add(New DataColumn("Lev elSubscription" ,
GetType(Boolean )))
7
8 ' Define dtLevels primary key
9 dtLevels.Primar yKey = New DataColumn()
{dtLevels.Colum ns("LevelName") }
10
11 dvLevels = New DataView(dtLeve ls, "", "LevelName" ,
DataViewRowStat e.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 cbLevelSubscrip tion As CheckBox =
CType(gvrLevel. FindControl("cb LevelSubscripti on"), CheckBox)
4 If cbLevelSubscrip tion.Checked Then
5 dkLevel = gvLevels.DataKe ys(gvrLevel.Row Index)
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
Mar 13 '07 #2
On Mar 13, 11:48 pm, Roland Dick <bris...@web.de wrote:
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.DataKe ys(gvrLevel.Row Index) 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

shapper schrieb:
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(B yVal sender As Object, ByVal e As
System.EventArg s) Handles gvLevels.Init
2
3 With gvLevels
4 .AutoGenerateCo lumns = False
5 .DataKeyNames = New String() {"LevelName" }
6 .DataSource = Levels_Fill()
7 .ID = "gvLevels"
8 End With
9
10 Dim bfLevelDescript ion As New BoundField
11 bfLevelDescript ion.DataField = "LevelDescripti on"
12 gvLevels.Column s.Add(bfLevelDe scription)
13
14 Dim tfLevelSubscrip tion As New TemplateField
15 tfLevelSubscrip tion.ItemTempla te = New
tfLevelSubscrip tion(ListItemTy pe.Item)
16 gvLevels.Column s.Add(tfLevelSu bscription)
17
18 gvLevels.DataBi nd()
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("Leve ls")
4 Dim dvLevels As DataView
5 dtLevels = Levels.GetAllLe vels().Tables(0 )
6 dtLevels.Column s.Add(New DataColumn("Lev elSubscription" ,
GetType(Boolean )))
7
8 ' Define dtLevels primary key
9 dtLevels.Primar yKey = New DataColumn()
{dtLevels.Colum ns("LevelName") }
10
11 dvLevels = New DataView(dtLeve ls, "", "LevelName" ,
DataViewRowStat e.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 cbLevelSubscrip tion As CheckBox =
CType(gvrLevel. FindControl("cb LevelSubscripti on"), CheckBox)
4 If cbLevelSubscrip tion.Checked Then
5 dkLevel = gvLevels.DataKe ys(gvrLevel.Row Index)
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
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(B yVal sender As Object, ByVal e As
System.EventArg s) Handles gvLevels.Load

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

End Sub ' gvLevels_Load

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

Response.Write( gvrLevel.RowInd ex.ToString)

Response.Write( gvLevels.DataKe ys(gvrLevel.Row Index.ToString) .Value.ToString ())
****

Now I get an exception on code line ****:
System.Argument OutOfRangeExcep tion: Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index at System.Collecti ons.ArrayList.g et_Item(Int32 index) at
System.Web.UI.W ebControls.Data KeyArray.get_It em(Int32 index) at ...

Any idea why?

Thanks,
Miguel

Mar 14 '07 #3
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(objec t sender, EventArgs e)
{
if (!this.IsPostBa ck)
{
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(o bject sender, EventArgs e)
{
this.lblSelecte dValues.Text = "";
foreach (GridViewRow row in this.GridView1. Rows)
{
CheckBox c = row.FindControl ("chkSelecte d") as CheckBox;
if (c != null)
{
if (c.Checked)
{
DataKey dk =
this.GridView1. DataKeys[row.DataItemInd ex];
if (dk != null)
this.lblSelecte dValues.Text +=
dk.Value.ToStri ng() + ", ";
}
}
}
}
And in the aspx:

<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns="False">
<Columns>
<asp:TemplateFi eld>
<ItemTemplate >
<asp:CheckBox ID="chkSelected " runat="server" />
</ItemTemplate>
</asp:TemplateFie ld>
<asp:BoundFie ld DataField="Leve lValue" Visible="False" />
<asp:BoundFie ld DataField="Leve lText" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button 1_Click"
Text="Button" />
<br />
<asp:Label ID="lblSelected Values" 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

shapper schrieb:
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(B yVal sender As Object, ByVal e As
System.EventArg s) Handles gvLevels.Load

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

End Sub ' gvLevels_Load

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

Response.Write( gvrLevel.RowInd ex.ToString)

Response.Write( gvLevels.DataKe ys(gvrLevel.Row Index.ToString) .Value.ToString ())
****

Now I get an exception on code line ****:
System.Argument OutOfRangeExcep tion: Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index at System.Collecti ons.ArrayList.g et_Item(Int32 index) at
System.Web.UI.W ebControls.Data KeyArray.get_It em(Int32 index) at ...

Any idea why?

Thanks,
Miguel
Mar 14 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2667
by: Steve | last post by:
I have a gridview which uses an objectdatasource for its select and delete. The delete command uses the function below. The delete itself works but the extra logic which requires parameters AccountDebitID and AccountCreditID does not work. 'Delete a transaction Sub deletetrans(ByVal transactionid As Integer, ByVal transactionamount
2
5640
by: needin4mation | last post by:
In a GridView, take for example a delete button. When I click the delete button in my GridView the GridView row is deleted and the GridView rebinds and refreshes the records to show accurately. Problem: I have a GridView that has a select. This select gives a FormView control the data to open. I set the GridView visible to false. I have only my FormView open. This FormView is used to edit, have other DetailsViews that open etc.
2
8992
by: Greg | last post by:
Hello, I am trying to bind a GridView to a custom object I have created. First, here is what I'm trying to do: I have a wizard for adding/editing Users. When the wizard begins, a User object (custom class) is created, and properties are populated in each step of the wizard. In one of the steps, the User is assigned to 1 or more Programs. Assigned Programs are stored by the User object in a List, and displayed in a GridView in the...
4
2604
by: Wannabe | last post by:
I am using ASP.Net 2.0 and have a gridview on my page. I have everything working except the delete command. The page reloads except the row I am trying to delete is still there. I believe it is something really easy, but I cannot see it. The stored procedue works when run in QA. Can someone tell me what I am doing wrong/missing that is keeping the delete command from working in the gridview? Thank you. I am trying to delete a row out of...
0
1787
by: Wannabe | last post by:
I am using ASP.Net 2.0 and have a gridview on my page. I have everything working except the delete command. The page reloads except the row I am trying to delete is still there. I believe it is something really easy, but I cannot see it. The stored procedue works when run in QA. Can someone tell me what I am doing wrong/missing that is keeping the delete command from working in the gridview? Thank you. I am trying to delete a row out of...
0
1244
by: Wannabe | last post by:
I have been trying to figure this out for days now...can someone please help? I am using ASP.Net 2.0 and have a gridview on my page. I have everything working except the delete command. The page reloads except the row I am trying to delete is still there. I believe it is something really easy, but I cannot see it. The stored procedue works when run in QA. Can someone tell me what I am doing wrong/missing that is keeping the delete...
8
9662
by: =?Utf-8?B?TWlrZSBSYW5k?= | last post by:
I am trying to get a list of files from a specified directory using the System.IO namespace classes, and then use that list as the datasource for a GridView. I have been able to do this successfully. The problem is when I try to hook up a HyperLinkField it's not working. Basically, what I want to end up with is to have the file name listed in the column and have the link point to the full file path, for each file in the list. I've been...
3
7402
by: =?Utf-8?B?U21pdGE=?= | last post by:
Hello all, I have a gridview, and a label inside the <Columnsand ItemTemplate. The label is a hidden. I want to retrieve the value of this label on the gridview_OnPageIndexChanged event, but i seem to get a nullexception. Can anyone please tell me what iam doing wrong. When i do the "view source" option i do see the values in the label. thanks for all the help
1
5029
by: needhelp1 | last post by:
I have gridview with a detailsview below. When I click on 'New' in brings up the DetailsView for inserting. When I click on 'Edit' in does not brink up the DetailsView. What am I doing wrong? I totally at a loss, please help. I don't know if I need to something to grdUserProfile_RowEditing. Thank you! This is some of my code behind: protected void grdUserProfile_RowEditing(object sender, GridViewEditEventArgs e) { } protected void...
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10101
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.