John Doe
John Doe

Reputation: 11

Is there a way to make GridView selectable?

I'm making an Uber-like website for a class project. In the code below I load data from a table in my database into a DataTable and then show the data in GridView.

Is there was a way to make gridview selectable? So if the person selects the first row of the grid and then presses a button, something will happen?

SqlCommand cmd = new SqlCommand("select * from LoggedIn where UserOccupation= @UserOccupation", con);
cmd.Parameters.AddWithValue("@UserOccupation", "Driver");

DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(dt);

if (dt.Rows.Count > 0)
{
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

Upvotes: 1

Views: 619

Answers (1)

Albert D. Kallal
Albert D. Kallal

Reputation: 49309

the most easy way is to add a button to the grid view.

the problem is if you just allow a "click" on a row, then then you have to spend time + effort to show/make the row highlight.

So, it is much easier to just drop a button into the grid view.

And I WILL show/note that once you drop that button on the row, then you CAN have a single click on the row to do the same as the button.

You can add this to the markup:

 <asp:GridView ID="GridView1" runat="server">
    <Columns>
      <asp:TemplateField>
         <ItemTemplate>
           <asp:Button runat="server" Text="Select" CommandName="Select"/>
         </ItemTemplate>
      </asp:TemplateField>
    </Columns>
 </asp:GridView>

Ok, so your (nice) simple code will fill the grid. Now the above WILL add a button to the first row. If you don't like that, then add this code snip to the gridview on row create:

Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated

    Dim myRow As GridViewRow = e.Row

    Dim myCell As TableCell = myRow.Cells(0)
    myRow.Cells.Remove(myCell)
    myRow.Cells.Add(myCell)

End Sub

So, the above will move the button to the end of the grid from the first row.

So if you just drop the button, you get this:

enter image description here

But, I like the button at the end of the grid, so if you add above code, then you get this:

enter image description here

NOTE careful - note SUPER DUPER careful: the key magic that makes this work is the CommandArguemnt

this tag in the button: CommandName="Select"

(select is not a guess or some name - it MUST be the keyword select).

Now, with the above button, then a click on the row will fire the selected Index changed event.

In that event, you can get the selected Index

eg:

    Debug.Print("row sel = " & GridView1.SelectedIndex)
    Dim mygridrow As GridViewRow = GridView1.SelectedRow

    Debug.Print("Hotel name = " & mygridrow.Cells(4).Text)

Last but not least:

do you really want this to fire with just a click on the row - not have to click on that button?

Ok then add this routine:

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Attributes("onclick") = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" & e.Row.RowIndex)
        e.Row.ToolTip = "Click to select this row."
    End If
End Sub

NOTE again: You MUST have that button on the grid for the above row-select to work. If you want, you can hide the button with a style="display:none", but you STILL need the one button on the gird - even if you hide it. So now the the button click or a click anywhere on the row will fire/trigger the rowindex changed event as we have above.

And for the row trick to work, you also have to add this to the page heading markup:

EnableEventValidation = "false"

eg: the above goes here:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="GridRowSel.aspx.vb" 
Inherits="WebEasy.GridRowSel"
EnableEventValidation = "false"%>

So not really 100% convinced that you want the row click - but above does work for a button, and if you really want the row click, then you can add that 2nd routine, and also don't forget the EnableEventValidation = "false" in the page heading markup.

Edit: comments question - selecting rows.

Well, the above was just a example. If one was to want the user say to select a bunch of rows.

This this approach:

Say this gv:

<h3>Hotels</h3>
<asp:GridView ID="GridView1" runat="server" Width="40%"
    AutoGenerateColumns="False" DataKeyNames="ID" 
    CssClass="table table-hover table-striped">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:CheckBox ID="chkSel" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<br />

<asp:Button ID="cmdShowSelected" runat="server" 
    Text="Show Selected hotels"
    CssClass="btn"
    OnClick="cmdShowSelected_Click" />
    <br />
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

Code to load gv:

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

    If Not IsPostBack Then
        LoadGrid()
    End If

End Sub

Sub LoadGrid()

    Dim cmdSQL As New SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName")
    GridView1.DataSource = MyrstP(cmdSQL)
    GridView1.DataBind()

End Sub

And code for the button below the gv:

Protected Sub cmdShowSelected_Click(sender As Object, e As EventArgs)

    Dim sPKList As String = ""
    For Each gRow As GridViewRow In GridView1.Rows

        Dim pkID As Integer = GridView1.DataKeys(gRow.RowIndex).Item("ID")
        Dim chkbox As CheckBox = gRow.FindControl("chkSel")

        If chkbox.Checked Then
            If sPKList <> "" Then sPKList &= ","

            sPKList &= pkID

        End If
    Next

    Label1.Text = $"List of PK id selected = {sPKList}"

End Sub

And we now have this result:

enter image description here

Upvotes: 1

Related Questions