Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

asp.net 4.0 vb gridview multi button in columnsl how to tell which button clicked

Status
Not open for further replies.

DougP

MIS
Dec 13, 1999
5,985
US
I have a gridview with several columns each containing one button.
I can get the row id but not the column id or the button caption.
I made them all Select buttons which is the only way it will work on a hosted WEB site.
any other type of button and the GridView1_RowCommand dose not fire.
I just want 3 buttons and know which one I pressed?

Code:
   Private Sub GridView1_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

        Dim index As Integer
        Dim selectedRow As GridViewRow

        index = Convert.ToInt32(e.CommandArgument)
        selectedRow = GridView1.Rows(index)
        Me.lblName.Text = selectedRow.Cells(0).Text
' the following 6 lines are code I got from another WEB teh rem'ed out lines don't work
        Dim currentCommand As String = e.CommandName
        Dim currentRowIndex As Integer = Int32.Parse(e.CommandArgument.ToString())
        'Dim ProductID As String = GridView1.DataKeys(index).Value 'this gives error

        Label1.Text = "e.CommandName: " & currentCommand
        Label2.Text = "e.CommandArgument.ToString: " & currentRowIndex.ToString
        'Label3.Text = "GridView1.DataKeys(index).Value: " & ProductID

    
        Dim cnn As SqlConnection
        Dim cmd As New SqlCommand

        cnn = New SqlConnection(gblconnectionString)

        Try

            cnn.Open()
            With cmd
                .Connection = cnn

                .CommandText = "Attend"
                .CommandType = CommandType.StoredProcedure

                .Parameters.AddWithValue("Lastname", Me.lblName.Text)
                .Parameters(0).SqlDbType = SqlDbType.Text
                Debug.Print(e.CommandName)
                Me.lblRowNumber.Text = e.CommandName.ToString
                If e.CommandName.ToString = "Select" Then
                    .Parameters.AddWithValue("Present", "P")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                    'ElseIf e.CommandName = "Absent" Then
                    '    .Parameters.AddWithValue("Present", "A")
                    '    .Parameters(1).SqlDbType = SqlDbType.Text
                Else
                    .Parameters.AddWithValue("Present", "T")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                End If

                .ExecuteNonQuery()

            End With

            Me.GridView1.DataBind()

        Catch ex As Exception
            MsgBox(Err.Number & " " & Err.Description)
        End Try

DougP
 
Any button you place in the grid will trigger the RowCommand. Did you place your buttons in a Template column?
 
No, I am just learning this. What else do I need to do?

DougP
 
OK here is what I have so far
I Have 3 buttons one in each column named Present, Absent, Tardy. The Gridview is bound to a SQL datasource. I added the 3 Select button columns after the fact.
I want to click the appropriate button and run the stored procedure passing a value that corresponds to the button pushed. Pressing 'Present' would send a 'P', Tardy a 'T' Absent an 'A'.

When I press the first button 'Present' it fires the GridView1_RowCommand event and selects the row. all 3 buttons select the correct row, fire the event, but since they are all Select buttons they all goto the top "IF" If e.CommandName.ToString = "Select" Then ...
Is there a way to find the "Header text of the column or the Select text of the button which both contain the correct words 'Tardy' or 'Absent'
My code says I pressed a select button. I want to know which select button I pressed. If I just add 'command' buttons instead of Select buttons it does not fire the event at all.
Code:
     Private Sub GridView1_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        Dim index As Integer
        Dim selectedRow As GridViewRow
        index = Convert.ToInt32(e.CommandArgument)
        selectedRow = GridView1.Rows(index)
        Me.lblName.Text = selectedRow.Cells(0).Text
        Dim currentCommand As String = e.CommandName
        Dim currentRowIndex As Integer = Int32.Parse(e.CommandArgument.ToString())
        Dim cnn As SqlConnection
        Dim cmd As New SqlCommand

        cnn = New SqlConnection(gblconnectionString)
        Try
            cnn.Open()
            With cmd
                .Connection = cnn
                .CommandText = "Attend"
                .CommandType = CommandType.StoredProcedure

                .Parameters.AddWithValue("Lastname", Me.lblName.Text)
                .Parameters(0).SqlDbType = SqlDbType.Text
                
                'the e.commandName is always 'Select' no matter which button is pressed
                If e.CommandName.ToString = "Select" Then
                    .Parameters.AddWithValue("Present", "P")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                ElseIf e.CommandName.ToString = "Tardy" Then
                    .Parameters.AddWithValue("Present", "T")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                Else
                    .Parameters.AddWithValue("Present", "A")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                End If
                .ExecuteNonQuery()
            End With
            Me.GridView1.DataBind()
        Catch ex As Exception
            MsgBox(Err.Number & " " & Err.Description)
        End Try
    End Sub

Please help this is the last step to making this work.

DougP
 
I can't see your HTML for the grid, which would help, but don't make the buttons a command column.
Put each button in a template column and assign what ever commandName you want to the button.
Something like:

Code:
<ItemTemplate>
   <asp:LinkButton ID="lbPresent" runat="server" CausesValidation="False" CommandName="Present"
      CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
<ItemTemplate>
   <asp:LinkButton ID="lbAbsent" runat="server" CausesValidation="False" CommandName="Absent"
      CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
<ItemTemplate>
   <asp:LinkButton ID="lbTardy" runat="server" CausesValidation="False" CommandName="Tardy"
      CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
 
Thanks for your quick reply :) here is my HTML.
total Newbie question: Ok I put this down there somewhere but gives error when running.
do I need to edit the Gridview and add something in there? you should be able to see my grid and buttons? I would also like them to be buttons not links, if possible.
Code:
<body>
    <form id="form1" runat="server">
    <div style="height: 362px">
    
        <asp:Label ID="lblGrade" runat="server" Text="3"></asp:Label>
&nbsp;&nbsp;
        <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
&nbsp;<asp:Label ID="lblSaved" runat="server" Text="Saved"></asp:Label>

        <asp:Button ID="btnNewDay" runat="server" Text="New Day" />
        <asp:Label ID="lblRowNumber" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataSourceID="SqlDataSource1" Height="168px" BackColor="White" 
            BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" 
            GridLines="Horizontal">
            <Columns>
                <asp:BoundField DataField="Lastname" HeaderText="Lastname" 
                    SortExpression="Lastname" />
                <asp:BoundField DataField="grade" HeaderText="Grade" SortExpression="grade" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="Present" HeaderText="Present" 
                    SortExpression="Present" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:CommandField ButtonType="Button" SelectText="Present" 
                    ShowSelectButton="True" HeaderText="Present" />
                <asp:CommandField ButtonType="Button" HeaderText="Absent" SelectText="Absent" 
                    ShowSelectButton="True" />
                <asp:CommandField ButtonType="Button" HeaderText="Tardy" SelectText="Tardy" 
                    ShowSelectButton="True" />
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>
        <asp:Label ID="lblEmail" runat="server" Text="Email: "></asp:Label>
        <asp:TextBox ID="txtEmail" runat="server" Width="193px"></asp:TextBox>
        <asp:Button ID="EmailReport" runat="server" Font-Size="Smaller" 
            Text="Email Report"  />

        <br />
--------------------- I put it here but gives error ----------- see below -----------
        <ItemTemplate> 
            <asp:LinkButton ID="lbPresent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Present" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
       </ItemTemplate> 
       <ItemTemplate> 
            <asp:LinkButton ID="lbAbsent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Absent" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
            </ItemTemplate> 
            <ItemTemplate> 
            <asp:LinkButton ID="lbTardy" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Tardy" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
            
            </ItemTemplate> 
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:robots2000ConnectionString %>" 
            SelectCommand="RetrieveStudentsbyGrade" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="lblGrade" Name="Grade" PropertyName="Text" 
                    Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
    
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
    
    </div>
    <br />

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30456: 'DataItemIndex' is not a member of 'Attend.Attend'.

Source Error:

Line 63: <br />
Line 64: <ItemTemplate>
Line 65: <asp:LinkButton ID="lbPresent"
Line 66: runat="server"
Line 67: CausesValidation="False"

DougP
 
The command argument can be whatever you want. In my example I am using the GridView RowIndex.
You have an error because you put the code outside of your grid. These are itemtemplates that go inside of the grid. You can change them to regular buttons as well.
 
Ok I opened the Gridview selected the buttons and clicked "Convert to Template field" link.
so it put the code in the correct place.
but now I get an error in the VB code on the following line.
index = Convert.ToInt32(e.CommandArgument)
it determines which row I clicked. without it nothing works.
this error happened after I converted the buttons to template.
Take the template stuff out it runs fine again.

HTML code gridview
Code:
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataSourceID="SqlDataSource1" Height="168px" BackColor="White" 
            BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" 
            GridLines="Horizontal">
            <Columns>
                <asp:BoundField DataField="Lastname" HeaderText="Lastname" 
                    SortExpression="Lastname" />
                <asp:BoundField DataField="grade" HeaderText="Grade" SortExpression="grade" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="Present" HeaderText="Present" 
                    SortExpression="Present" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>

                  <asp:TemplateField HeaderText="Present" ShowHeader="False">
                      <ItemTemplate>
                          <asp:Button ID="Button1" runat="server" CausesValidation="False" 
                              CommandName="Select" Text="Present" />
                      </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Absent" ShowHeader="False">
                    <ItemTemplate>
                        <asp:Button ID="Button2" runat="server" CausesValidation="False" 
                            CommandName="Select" Text="Absent" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Tardy" ShowHeader="False">
                    <ItemTemplate>
                        <asp:Button ID="Button3" runat="server" CausesValidation="False" 
                            CommandName="Select" Text="Tardy" />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>

VB code
Code:
   Private Sub GridView1_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

        Dim index As Integer
        Dim selectedRow As GridViewRow
        index = Convert.ToInt32(e.CommandArgument)  ' <<<< ERROR ON THIS LINE when a button is clicked
        selectedRow = GridView1.Rows(index)
        Me.lblName.Text = selectedRow.Cells(0).Text
        Dim cnn As SqlConnection
        Dim cmd As New SqlCommand
        cnn = New SqlConnection(gblconnectionString)
        Try
            cnn.Open()
            With cmd
                .Connection = cnn
                .CommandText = "Attend"
                .CommandType = CommandType.StoredProcedure
                .Parameters.AddWithValue("Lastname", Me.lblName.Text)
                .Parameters(0).SqlDbType = SqlDbType.Text
                Debug.Print(e.CommandName)
                Me.lblRowNumber.Text = e.CommandName.ToString
                'the e.commandName is always 'Select' no matter which button is pressed
                If e.CommandName.ToString = "Select" Then
                    .Parameters.AddWithValue("Present", "P")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                ElseIf e.CommandName.ToString = "Tardy" Then
                    .Parameters.AddWithValue("Present", "T")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                Else
                    .Parameters.AddWithValue("Present", "A")
                    .Parameters(1).SqlDbType = SqlDbType.Text
                End If
                .ExecuteNonQuery()
            End With
            Me.GridView1.DataBind()
        Catch ex As Exception
            MsgBox(Err.Number & " " & Err.Description)
        End Try

DougP
 
You don't have a commandArgument for each of the buttons. Use the code I gave you:
Code:
<asp:Button ID="Button1" runat="server" CausesValidation="False" 
   CommandName="Select" Text="Present" [b][COLOR=red]CommandArgument="<%# Container.DataItemIndex %>[/color][/b]" />
 
No when I paste that in it destroys the whole grid

this is ASP.NET 4.0 in Vis. WEB. Dev. 2010 VB.

Is there anyway to just get the word "Tardy" out of the button when I press it?
I cannot understand why we got this far in .NET Programming and have so much trouble just to get a caption from a button being pressed??? Rube Goldberg would be proud !
Code:
                <asp:CommandField ButtonType="Button" SelectText="Present" 
                    ShowSelectButton="True" HeaderText="Present" />
                <asp:CommandField ButtonType="Button" HeaderText="Absent" SelectText="Absent" 
                    ShowSelectButton="True" />
                <asp:CommandField ButtonType="Button" HeaderText="Tardy" SelectText="Tardy" 
                    ShowSelectButton="True" />
               [COLOR=red][b] <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Select" 
                     Text="Present" CommandArgument="<%# Container.DataItemIndex %>" />[/b][/color]
            </Columns>

DougP
 
you are having problems because you are not following my directions.

Just paste my original code:
Code:
   <ItemTemplate> 
            <asp:LinkButton ID="lbPresent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Present" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
       </ItemTemplate> 
       <ItemTemplate> 
            <asp:LinkButton ID="lbAbsent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Absent" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
            </ItemTemplate> 
            <ItemTemplate> 
            <asp:LinkButton ID="lbTardy" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Tardy" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton>
Into the <columns> collection of the grid
This will work. You can change them to Buttons after you get it working.


 
Error Creating Control - GridView1System.Web.UI.WebControls.DataControlFieldCollection must have items of type 'System.Web.UI.WebControls.DataControlField'. 'ItemTemplate' is of type 'System.Web.UI.HtmlControls.HtmlGenericControl'.

DougP
 
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Attend.aspx.vb" Inherits="Attend.Attend" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
<html xmlns="<head runat="server">
<title></title>
<style type="text/css">
#form1
{
height: 365px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 362px">

<asp:Label ID="lblGrade" runat="server" Text="3"></asp:Label>
&nbsp;&nbsp;
<asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
&nbsp;<asp:Label ID="lblSaved" runat="server" Text="Saved"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID="btnNewDay" runat="server" Text="New Day" />
<asp:Label ID="lblRowNumber" runat="server" Text="Label"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" Height="168px" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal">
<Columns>

<ItemTemplate> <asp:LinkButton ID="lbPresent" runat="server" CausesValidation="False" CommandName="Present" CommandArgument="<%# Container.DataItemIndex %>"> </asp:LinkButton> </ItemTemplate> <ItemTemplate> <asp:LinkButton ID="lbAbsent" runat="server" CausesValidation="False" CommandName="Absent" CommandArgument="<%# Container.DataItemIndex %>"> </asp:LinkButton> </ItemTemplate> <ItemTemplate> <asp:LinkButton ID="lbTardy" runat="server" CausesValidation="False" CommandName="Tardy" CommandArgument="<%# Container.DataItemIndex %>"> </asp:LinkButton>
</Columns>

<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:Label ID="lblEmail" runat="server" Text="Email: "></asp:Label>
<asp:TextBox ID="txtEmail" runat="server" Width="193px"></asp:TextBox>
<asp:Button ID="EmailReport" runat="server" Font-Size="Smaller"
Text="Email Report" />


<br />


<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:robots2000ConnectionString %>"
SelectCommand="RetrieveStudentsbyGrade" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="lblGrade" Name="Grade" PropertyName="Text"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

</div>
<br />
</form>
</body>
</html>


DougP
 
ok, try this, you need each ItemTemplate in a TemplateField:
Code:
 <asp:TemplateField>
<ItemTemplate> 
            <asp:LinkButton ID="lbPresent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Present" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
       </ItemTemplate> 
  </asp:TemplateField>
 <asp:TemplateField>
       <ItemTemplate> 
            <asp:LinkButton ID="lbAbsent" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Absent" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
            </ItemTemplate> 
  </asp:TemplateField>
 <asp:TemplateField>
            <ItemTemplate> 
            <asp:LinkButton ID="lbTardy" 
            runat="server" 
            CausesValidation="False" 
            CommandName="Tardy" 
            CommandArgument="<%# Container.DataItemIndex %>">
            </asp:LinkButton> 
  </asp:TemplateField>
 
NO same problem it destroys the grid ...
I am using ASP.NET 4.0 I know you can't assume old code works in the new versions

it does not like this line
CommandArgument="<%# Container.DataItemIndex %>">
what is that line supposed to do? is it going to tell me I pressed "Tardy" or "Absent" later on?
what's with the "#" symbol is that C# code? I'm using VB.





DougP
 
Here is what I did to make it work for now.
I added 3 bottoms outside the grid, Present, Tardy, Absent.
I have one select button in the grid to select each row row.
So I select a row then pick one of the 3 other buttons and that works.





DougP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top