Selecting a value from a gridview selected row

i am trying to select a value from a selected row in a gridview. the value i want to select is "workordernumber"  i have the gridview displaying a list of work orders.  the list changed depending on whether or not the person has chosen to view open, closed or all work orders.  if i am view just the open or closed work orders it is obviously not showing every single work order number and there are some gaps in there.  when i try to select the value of the work order number cell with the select button it is acting kinda funky.  it is selecting the index value instead of the value of the cell.  i am trying to use the value of this number on the next page so the person can update the work order. 

for testing purposes i am just writing the value to a label on the page, so the code i am using is: label2.text = gridview2.selectedrow.cells(1).text.  i have also tried creating a gridviewrow from the selected row and it is giving me the same problem.  i can post a link to the site i am trying to work on if that is ok, but i am not sure whether or not that is a good idea.  if you guys think it is then i will do that so you can see my problem firsthand.  i am working on it throughout the day so it will be changing alot.

i am new to this stuff so i am hoping it is just something stupid.  thank you for you help. 

0
phreaqe
3/15/2007 5:28:13 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

14 Replies
1111 Views

Similar Articles

[PageSpeed] 8

This code will parse thru the entire gridview for selected rows

foreach (GridViewRow r in GridView1.Rows)
        {
            if (r.RowState== DataControlRowState.Selected)
            {
               label2.text = r.Cells[1].Text;
            }
        }


Let the game begin!!

Barcode image generation made easy.
Writing an ActiveX Control in C#
Generating Relational Data From XML Datatype -Part 1
Generating Relational Data From XML Datatype -Part 2
Dynamic XML From SQL Server
0
imran
3/15/2007 9:45:34 PM
imran.nathani:

This code will parse thru the entire gridview for selected rows

foreach (GridViewRow r in GridView1.Rows)
        {
            if (r.RowState== DataControlRowState.Selected)
            {
               label2.text = r.Cells[1].Text;
            }
        }

thank you for the reply, and please forgive my newbness, i am writing this in VB instead of c#, and when i try to use GridViewRow it tells me that it is a type and cannot be used as an expression.  what should i use to make that work.  thank you for you help

0
phreaqe
3/15/2007 10:04:54 PM

try this....

For Each r As GridViewRow In GridView1.Rows
    If (r.RowState = DataControlRowState.Selected) Then
        label2.text = r.Cells(1).Text
    End If
Next


Let the game begin!!

Barcode image generation made easy.
Writing an ActiveX Control in C#
Generating Relational Data From XML Datatype -Part 1
Generating Relational Data From XML Datatype -Part 2
Dynamic XML From SQL Server
0
imran
3/15/2007 10:32:19 PM

Instead of trying to read the cells, try to read the underlying data:

((DataRowView)SelectedRow.DataItem)["myfield"]


Greetings,

Sjonnie
0
Sjonnie2nd
3/15/2007 10:32:53 PM

Or..
If "workordernumber" is part of the DataKeyNames you also could use the DataKeys property.


Greetings,

Sjonnie
0
Sjonnie2nd
3/15/2007 10:35:44 PM
ok so i have the question above figured out, but it still is not selecting the correct value, until i click select 2 times.  any ideas why it would be doing that? let me know what code you need to see.  like i said in the original post i can link to the site i am creating this on if thats allowed, and considered safe and whatnot.  i dont want to do it if it will mess up my site even more or anything.  thank you for your help. - Mark
0
phreaqe
3/15/2007 10:39:41 PM
imran.nathani:

try this....

For Each r As GridViewRow In GridView1.Rows
    If (r.RowState = DataControlRowState.Selected) Then
        label2.text = r.Cells(1).Text
    End If
Next

 

thats just what i did, i just did not see all these replies.  woops.  thank you very much. 

0
phreaqe
3/15/2007 10:49:14 PM
Sjonnie2nd:

Or..
If "workordernumber" is part of the DataKeyNames you also could use the DataKeys property.

 

i tried that earlier today but was unable to figure out how to make it work.  it seems like the idea above with teh for each loop is working except that i have to click the select button 2 times to acually get it to select the right value.  if i click the select button then it displays all the data twice.  it diplays it al and then displays it all over agian. 

0
phreaqe
3/15/2007 10:53:37 PM
I think it's time you show us the aspx en aspx.cs (or vb?) code :)
Greetings,

Sjonnie
0
Sjonnie2nd
3/15/2007 11:51:15 PM

Sjonnie2nd:
I think it's time you show us the aspx en aspx.cs (or vb?) code :)

all the stuff that is commented out are things that i tried that didnt work but was keeping around just as references.  i know its not the best code but i am pretty new to this.  i hope this helps. if you need any other code let me know. 

i originally had the gridview being databound on the page load, but when i moved that to the button click even then it got rid of having 2 copies of the data being displayed.

Imports System.Data.SqlClient

Imports

System.data

Partial

Class View_Work_Orders

 

Inherits System.Web.UI.Page

Dim DS As New DataSet

#

Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.

<System.Diagnostics.DebuggerStepThrough()>

Private Sub InitializeComponent()

End Sub

 

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

'CODEGEN: This method call is required by the Web Form Designer

'Do not modify it using the code editor.

InitializeComponent()

End Sub

#

End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load

End Sub

 

'Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged

' Dim Id As Int16

' Dim row As GridViewRow = GridView2.SelectedRow

' Label1.Text = GridView2.SelectedRow.Cells(1).Text

' Id = GridView2.SelectedIndex

' Session.Add("SelectedWorkOrder", Id)

' 'Response.Redirect("Work Order.aspx")

' 'Label1.Text = DS.Tables("WorkOrder").Rows(GridView2.SelectedIndex).Item("WorkOrderNumber").ToString

'End Sub

Sub GridView2_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs) Handles GridView2.SelectedIndexChanging

'Dim Id As Int16

'Dim row As GridViewRow ' = GridView2.Rows(e.NewSelectedIndex)

For Each r As GridViewRow In GridView2.Rows

If (r.RowState = DataControlRowState.Selected) Then

Label2.Text = r.Cells(1).Text

End If

Next

'Label2.Text = GridView2.SelectedRow.Cells(1).Text

'Label2.Text = row.Cells(1).Text

'ID = GridView2.SelectedRow.Cells(1).Text

'Id = row.Cells(1).Text

' Session.Add("SelectedWorkOrder", Id)

'Label2.Text = HttpContext.Current.Session("SelectedWorkOrder").ToString

'Response.Redirect("Work Order.aspx")

'Label1.Text = DS.Tables("WorkOrder").Rows(GridView2.SelectedIndex).Item("WorkOrderNumber").ToString

End Sub

Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnsubmit.Click

Dim con As String = "Data Source=cscsql.cc.edu;Initial Catalog=c450;User ID=c450;Password=*******;"

Dim aconn As New SqlConnection(con)

Dim DA1 As New SqlDataAdapter("SELECT [WORKORDERNUMBER], [Title], [ReqName], [Type], [Priority], [TechName] FROM [JoinedWO]", aconn)

'Dim DS As New DataSet

DA1.Fill(DS,

"WorkOrder")

GridView2.Visible =

True

GridView2.DataSource = DS

GridView2.DataBind()

If ddlView.SelectedValue.Equals("1") Then

Dim DA As New SqlDataAdapter("SELECT [WORKORDERNUMBER], [Title], [ReqName], [Type], [Priority], [TechName] FROM [JoinedWO] WHERE [STATUSID] =1", aconn)

Dim DS As New DataSet

DA.Fill(DS,

"WorkOrder")

GridView2.Visible =

True

GridView2.DataSource = DS

GridView2.DataBind()

ElseIf ddlView.SelectedValue.Equals("2") Then

Dim DA As New SqlDataAdapter("SELECT [WORKORDERNUMBER], [Title], [ReqName], [Type], [Priority], [TechName] FROM [JoinedWO] WHERE [STATUSID] = 2", aconn)

Dim DS As New DataSet

DA.Fill(DS,

"WorkOrder")

GridView2.Visible =

True

GridView2.DataSource = DS

GridView2.DataBind()

ElseIf ddlView.SelectedValue.Equals("3") Then

Dim DA As New SqlDataAdapter("SELECT [WORKORDERNUMBER], [Title], [ReqName], [Type], [Priority], [TechName] FROM [JoinedWO]", aconn)

Dim DS As New DataSet

DA.Fill(DS,

"WorkOrder")

GridView2.Visible =

True

GridView2.DataSource = DS

GridView2.DataBind()

End If

End Sub

Protected Sub btnnew_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnnew.Click

Response.Redirect(

"NewWO.aspx")

End Sub

Protected Sub btnlogout_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnlogout.Click

Session(

"loggedin") = "false"

Response.Redirect(

"default.aspx")

End Sub

End

Class
0
phreaqe
3/16/2007 12:07:05 AM

ok i have part of it fixed now.  i moved this code:

For Each r As GridViewRow In GridView2.Rows If (r.RowState = DataControlRowState.Selected) Then

Label2.Text = r.Cells(1).Text

End If Next

from the selectedindexchanging to the selectedindexchanged and now it kinda works.  it selects the value on the first click, but it is not selecting all of them. it is only selecting the value on every other cell.  if i am displaying all the work orders it will select 1,3,5,7 but not 2,4,6. any ideas?

thank you for your help so far.  i would not be as far as i am without your help.  i appreciate it.

-Mark 

0
phreaqe
3/16/2007 2:57:29 AM

imran.nathani:
Label2.Text (Label2.Text + r.Cells(1).Text)

all that does is make the label display the default text of "label" + the number i have selected.  so it shows "label1" and it is still getting every other line. 

any other suggestioins?

-Mark 

0
phreaqe
3/16/2007 2:38:48 PM

I dont have an explanation why it doesnt work but perhaps it brings you in a direction:

- The iteration is not needed, GridView.SelectedRow will do.
- You are databinding 2 times. This isn't a problem but not very efficient. Can't u place the first databind() into an "else" part?
- In your aspx, are you perhaps doing something with an AlternatingRowStyle or something?


Greetings,

Sjonnie
0
Sjonnie2nd
3/16/2007 11:23:30 PM
Reply:

Similar Artilces:

Iwant to select a row and column in gridview with select radiobutton. but No checked change event.below put a button .if click that button to seleced row values will select
I want to select a row and column in gridview using radiobutton in gridview . if which radio button is select that row will select and i want that row column values in outside individual textboxes of next page.  but in that only single radiobutton will select and no post back="true" bcz iam not using checked change property. i inserted button below gridview. if i click the that selected row and columns values are stored into textboxes of next page im using this code .but im getting one column in that row. but i want all columns in that selected row so plz repla...

Select a row in GridView and show dependent Values in Other GridView on the basis of selection...
hi, i've a parent table which has many values in it.. i also have some child tables which contains other information.. these tables are linked through forein keys... now what i want to do is, i want to select a value from main table suppose, ID 10, and i want to display it in other gridview having the children table values of the ID 10. how can i achieve this scenario? Please let me know if i am not clear with my statements. Thank U-Jigzy-Please remember to click “Mark as Answer” on the post that helps you.This can be beneficial to other members reading the thread. You can have y...

Problem in Using DropDownList Control to select a selected row of SqlDataSource that is under GridView Control
Hi all,In my SQL Server Management Studio Express, I have a database "ChemDatabase" that has a table "LabData"  formatted in the following way: SampleID int PRIMARY KEY, SampleName nvarchar(25), ChemicalName, nvarchar(25), Concentration decimal(6.2) with 5 rows of records in this .dbo table. In my Visual Web Developer Express, I created a website "RPD-TCE" for extracting a row of record from the LabData table by using a DropDownList, a GridView and a SqlDataSource.  I want to click DropDownList to list one number of S...

Gridview paging enabled. Has checkbox to select the row . If user select the checkbox on one page and move to 2nd page to select the rows there also to export the selected rows to excel. But doing so
HiI am using Gridview and that has paging enabled. Using checkbox to select the particular row of the gridview to export the selected rows to the excel . Everything is working fine except for one case.Let user selected the "check" box for, five rows which user would like to export to excel (two of rows on page 1 of results and 3 of them on page 2 of results), however it only exports the 3 row details from page 2, because it seems to de-select the 2 rows from page 1 when I move to page 2 and vice versa. The code i am using is as :protected void BtnExcel_Click(object sender, EventArg...

Selecting a gridview row and keeping the last selected row in a gridview highlighted after mouse moves over a new row.
What is the best way to show a gridview row highlighted once selected and keep it highlighted once the mouse moves over a different row? Thanks, Steve hi,you can use <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="#FFFFFF" /> plz let me know if i misunderstood you Thanks for your help. One problem; however, is that after the row has been selected and I check the "grid.SelectedIndex" it has a value of -1 and not the index of the row that was selected on the grid. What do you recommend? Thanks, Steve hi, sorry i din...

Selecting the multiple rows in GridView and inserting the selected rows to another Gridview & Performing some operations on it
 Dear All, I have become mad for solving this problem. Please Help me. I have a Gridview bound to a datasource. I inserted the CheckBox Control in Templet to select certain rows. Gridview1 contains some products id & name.I want to insert the selected rows in to second Gridview  and in the second Gridview I need to add two more colums AdvicedQty & AcceptedQty(TextBox Cotrol).The user will select few products in Gridview1 & clicks add which will be added another gridview then in second Gridview he enters the AdviceQty & AcceptedQty.After entering the data he cli...

I can't get value of control in the selected row of a Gridview
I'm trying to perform an update using a sqldatasource from a gridview after a selection is made from a dropdown and a linkbutton "lbnUpdate" is clicked. I assigned  "select" as the command name of the linkbutton so I was assuming that I could then reference the gridviews selected row from the code behind but I guess I made a bad assumption. During debug there is "nothing" in the variable I use to capture the gridview selected row. I will post what I have. If I set AutoGenereateSelect button to true I can get the SelectedIndexChanged event...

How to display the more than one row with items and buttons in gridview control. when i select three items at same time from categories(Fruits, Apples, Gifts). The selected items are displayed in g
Hi,when i select three items at same time from categories(Fruits, Apples, Gifts). The selected items are displayed in gridview.Here i would like to change this way "when i click more than one category at same time. it should be display selected item and button."For example: if i have to select Fruits, Apples from categories.  it should be display like 1st "row have Fruits and In 2nd row have Apples and button" in gridview.the button have some event.How can i do it? Please can anyone answer me.With kind requestThanks your query is very raw..can u details it out...Pl...

selecting row in gridview by clicking anywhere in row (not just on 'select' link)
Hi there- I would like my gridview to behave such that a click anywhere in the (whole length of the) row would act just like clicking the "select" column link. Anyone have any code or suggestions?   You could use: ( but you would also need to disable event validation ) <%@ Page Language="VB" EnableEventValidation="false"%> Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes.Add("onclick", "javascript:__doPostBack('GridView1','select$" &...

How to bind gridview depending on the selected value of dropdownlistbox present in same gridview.
I have a gridview, in that ihave dropdownlistbox as acolumn. Depending on the selected value of dropdown list box i want to bind the grid view. I know the concept that we need to bind the grid in selected index change of dropdownlistbox, But i am not getting the dropdownlistbox inside the selectedindex changed event of dropdownlistbox. How i can get the selectedindex of dropdownlistbox present in gridview.  Use the sender parameter to retrieve a reference to your DropDownList like so: protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)...

Select a gridview row without a select button
Hi Does anyone have a vb code sample of how to select a gridview row without having to click on a select button?   Thanks    ASPX <asp:label id="Label1" runat="server" /> <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" datakeynames="ProductID,ProductName" datasourceid="SqlDataSource1" style="margin-top: 12px;"> <columns> <asp:boundfield datafield="ProductID" headertext="ProductID" readonly="True" sort...

How to access the row cells value of gridview on Select button click in Gridview
Hi Friends I am trying to getting the Row cells value on the Select command click. PLz any one know then reply me.  just add the code below between <Columns> element<asp:CommandField ShowSelectButton="True" />  then in you code add GridView1_SelectedIndexChanging events . inside the events you can get te id either  by writig id=GridView1.SelectedRow.cells[0].tostring or temp string= ctype(GridView1.Rows(e.NewSelectedIndex).FindControl(controlname),label)).textnote : assume that the ID is handled by label control in your datagrid.good luck&quo...

GridView control Selected Value
I have a grid control on the page, which displays 10 rows per page and paging is enabled. I want to select two values in checkbox and go to next page and select some other value and so on. How do I get the selected value across page? Is there any default property available that I can call and get the selected value across on all the pages that user navigated?   Please help me out here.   Thanks   Hi, pandi: I suggest you can add a ArrayList or other collection in your viewstate or session of the page and put the selected value of the checkbox in to the ArrayList in Pag...

Selecting a value from a Gridview Control
I'm trying to get a value from a gridview control and put that value in a query string.  I have a select button on the gridview and once the user hits the select button i want to capture the the userid.  Here's some example code and you can see where i'm trying to do this in on the line that starts with Response.Redirect:     protected void SearchUserMenu_MenuItemClick(object sender, MenuEventArgs e)     {         if (GridView1.SelectedIndex > -1)         {             switch (e...

Web resources about - Selecting a value from a gridview selected row - asp.net.presentation-controls

Consultation Document on the Methods for Selecting the Chief Executive and for Forming the LegCo in 2012 ...
The " Consultation Document on the Methods for Selecting the Chief Executive and for Forming the LegCo in 2012 " was a document published on ...

Voting Machine Caught on Camera Casting Ballot for Democrat when Selecting Republican - YouTube
**UPDATE.... I've heard many reports that this is "just a calibration issue." I will say this... when I went to page 2 and began voting for city ...

Selecting decor that will move with the times
What colours should I use in my home so that my d&#233;cor is neutral and flexible but not boring?

Clock ticking on selecting successor to Leigh Clifford at Qantas
With Qantas on course to chalk up its largest annual profit since 2008, the question now is whether chairman Leigh Clifford is looking to hang ...

More to selecting political background music than indiscriminate meandering
Gathering a song to use as a protest weapon can backfire.

Jackie French: Why selecting the right place for your plants is important
The secret of growing anything easily is to choose the best spot for what you want to grow.

Liberals begin 'super weekend' of selecting delegates
A race for the top job in the federal Liberal party gained momentum on Friday as rank and file party members began the selection process for ...

Boston Marathon bombing trial: Judge, lawyers face challenges in selecting jurors - CTV News
As the second phase of jury selection began in the federal death penalty trial of Boston Marathon bombing suspect Dzhokhar Tsarnaev, it immediately ...

Selecting cabinet one of first orders of business for Trudeau
One of the first orders of business for any new prime minister is picking a cabinet. Who is likely to make the cut?

Agile Analysis, Self-Selecting Teams, TDD & BDD in Methods & Tools Winter 2014 issue
... for software developers, testers and project managers – has just published its Winter 2014 issue that discusses Agile Analysis, Self-Selecting ...

Resources last updated: 12/9/2015 1:07:19 AM