I am new to Vb.net.
I am using gridview and binding it a resultset from database. I am trying to use asp button and associate a codebehind function with it.
But since the rows are generating dynamically, ids of button are incrementing accordingly.
Here is the code -
'<asp:GridView ID="grdProjects" runat="server" CssClass="q_acontent" Width="990px"
AutoGenerateColumns="false" CellPadding="2" ClientIDMode="static" ViewStateMode="Enabled">
<asp:TemplateField HeaderText="Document Name">
<ItemTemplate>
<asp:Button ID="Button3" runat="server" Text='<%# (Convert.ToString(DataBinder.Eval(Container.DataItem, "Data_text")))%>'/>
</ItemTemplate>
<ItemStyle Width="5%" HorizontalAlign="Center" CssClass="conatact_phone breakword" />
</asp:TemplateField>
</asp:GridView>'
Please help me how to associate codebehind function and pass its corresponding button text to it.
Use the OnCommand event of button controls and Set the CommandArgument property of the button to your DataItem value as:
<ItemTemplate>
<asp:Button ID="Button3" runat="server"
Text='<%# (Convert.ToString(DataBinder.Eval(Container.DataItem,"Data_text")))%>'
OnCommand="Button3_Command"
CommandArgument='<%# (Convert.ToString(DataBinder.Eval(Container.DataItem,
"Data_text")))%>'
/>
</ItemTemplate>
OnCommand event in your code behind file:
Public Sub Button3_Command(sender As Object, e As CommandEventArgs)
Dim _dataText As String = e.CommandArgument.ToString()
End Sub
Related
I have following gridview in aspx page:
<asp:GridView Runat="server" id="gv1" PageSize="20" Visible="False" AllowPaging="True" Width="100%"
CssClass="clsDataGrid" AutoGenerateColumns="false" DataKeyNames="intProofSLNo,txtAdminRemarks" CommandArgument='Eval(intProofSLNo,txtAdminRemarks)'
OnRowCommand="gv1_RowCommand" OnRowDataBound ="gv1_OnRowDataBound" >
<asp:BoundField DataField="intProofSLNo" ReadOnly="True" Visible="false" ItemStyle-Wrap="false" HeaderText="Sl No" ItemStyle-CssClass="clsNormalText"></asp:BoundField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnApprove" runat="server" CommandName="Approve" Text= "Approve / " />
<asp:LinkButton ID="lnkbtnReject" runat="server" CommandName="Reject" Text= "Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Admin Remarks">
<ItemTemplate>
<asp:Label ID="lblAdminRemarks" runat="server" ItemStyle-Wrap="True" Text='<%# Bind("txtAdminRemarks")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAdminRemarksEdit" runat="server" cssclass=clsCommonInput MaxLength="252" Text='<%# DataBinder.Eval(Container.DataItem, "txtAdminRemarks")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" Text="Edit" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" Width="38" runat="server" Text="Update|" CommandName="Update"CommandArgument='<%# Container.DataItemIndex %>' CausesValidation="true" ToolTip="Save"> </asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Width="40" Text="Cancel" CommandName="Cancel"
CausesValidation="false" ToolTip="Reset"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The user clicks on the 'Edit' link which makes 'Update' and 'Cancel' links visible.It then enters the remarks in the textbox and clicks 'Update'.A row command event is fired which updates the remarks in DB for the entry in that particular row. The same event calls the bind function:
Protected Sub gv1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Update" Then
//some code to update remarks//
gv1.EditIndex = -1
subBindDataGrid()
End If
The subBindDataGrid() fires the following rowbound event which hides the buttons depending on admin remarks:
Protected Sub gv1_OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblAdminRemarks As Label = DirectCast(e.Row.FindControl("lblAdminRemarks"), Label)
Dim lnkReject As LinkButton = DirectCast(e.Row.FindControl("lnkbtnReject"), LinkButton)
Dim lnkApprove As LinkButton = DirectCast(e.Row.FindControl("lnkbtnApprove"), LinkButton)
Dim lnkEdit As LinkButton = DirectCast(e.Row.FindControl("lblEdit"), LinkButton)
If DataBinder.Eval(e.Row.DataItem, "txtAdminRemarks").ToString().Trim = "Auto-Approved" Then
lnkApprove.Visible = False
lnkReject.Visible = False
lnkEdit.Visible = False
Else
lnkbtnApprove.Visible = True
lnkbtnReject.Visible = True
End If
End If
The remarks get updated in the DB. However, there is some issue in binding and instead of displaying the grid, the page is redirected to an error page. There is no exception thrown anywhere while debugging. The same events are also called in 'Edit'command. However, the functionality works fine there.Please suggest if there is anything wrong with the syntax.
I see you don't define a DataSourceID on the GridView static definition, please make sure you define a DataSource for the GridView in the subBindDataGrid procedure, otherwise it will have a null datasource in input.
Apologies for the slightly convoluted title.
Basically, I have a project where I have a database connected to it. I'm displaying some of the contents of the database using a GridView, which is all up and running, but the way I'm designing the page I need to be able to click a button in each row that in essence exports the value of one of the cells in the row to a subroutine.
I've tried googling it quite a bit and trying related things I found here, but nothing I could find would function like I would like it to.
The relevant code is below.
Markup:
<asp:GridView ID="Staffgv" runat="server" AutoGenerateColumns="false" OnRowCommand="Staffgv_RowCommand" AllowPaging="true" PageSize="20" OnPageIndexChanging="Staffgv_PageIndexChanging" BackColor="#f9f9f9" CssClass="gvStyle" >
<Columns>
<asp:TemplateField HeaderText="Start" InsertVisible="False" SortExpression="DateTimeStart">
<HeaderStyle Width="70px" CssClass="hdrGvStart"/>
<ItemTemplate>
<asp:Label ID="lblDateTimeStart" runat="server" Text='<%# Bind("DateTimeStart", "{0:t}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Finish" SortExpression="DateTimeEnd">
<HeaderStyle Width="70px" CssClass="hdrGvFinish"/>
<ItemTemplate>
<asp:Label ID="lblDateTimeEnd" runat="server" Text='<%# Bind("DateTimeEnd", "{0:t}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Forename" SortExpression="Forename">
<HeaderStyle Width="140px" CssClass="hdrGvForename"/>
<ItemTemplate>
<asp:Label ID="lblForename" runat="server" Text='<%# Bind("Forename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Surname" SortExpression="Surname">
<HeaderStyle Width="140px" CssClass="hdrGvSurname"/>
<ItemTemplate>
<asp:Label ID="lblSurname" runat="server" Text='<%# Bind("Surname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderStyle CssClass="gvHeaderEdit" />
<ItemTemplate>
<asp:Button ID="Btnapptid" runat="server" Text="" CssClass="btnGVEdit" CommandName="FillStaffTables" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the relevant VB code:
Private Sub Staffgv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Staffgv.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim row = DirectCast(e.Row.DataItem, DataRowView)
Dim apptid As Integer = Integer.Parse(row("AppointmentID").ToString)
Dim Btnapptid = DirectCast(e.Row.FindControl("Btnapptid"), Button)
'Btnapptid.Text = apptid
Btnapptid.ToolTip = apptid
End Select
End Sub
Protected Sub Staffgv_RowCommand(ByVal sender As Object, e As GridViewCommandEventArgs)
If (e.CommandName = "FillStaffTables") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
lblTxtTester.Text = "AppointmentID"
TextboxTester.Text = index
End If
End Sub
If anyone would like more code like the code used to fill the GridView I'll post it, just didn't want to post too much irrelevant code.
Thanks
Solution A
When you only want 1 value from the gridview row when the button is clicked.
You could simply utilize the CommandArgument of your button (Btnapptid). This assumes that you don't need the gridview row index for when the button is clicked. If you do need this, then please see Solution B, otherwise continue here.
First, you'd need to modify your button's CommandArgument in the aspx page
ASPX
<asp:Button ID="Btnapptid" runat="server" Text="" CssClass="btnGVEdit"
CommandName="FillStaffTables" CommandArgument='<%# Bind("AppointmentID") %>'/>
Then you should be able to grab the AppointmentID like this
VB (inside Staffgv_RowCommand())
If (e.CommandName = "FillStaffTables") Then
txtAppointmentID.Text = e.CommandArgument
End If
Solution B
When you need more than 1 value from the gridview row when the button is clicked
Please note that this solution requires a couple changes on your end
Create an additional control (in the gridview) which should hold the value that you want to get when the button is clicked.
Fill said control with the value you want (via Bind() in the UI or in RowDataBound in the codebehind).
Next, in your RowCommand you'd be able to grab the newly created control with the help of the index variable (from your example) like so
Staffgv.Rows(index).FindControl("YOUR_CONTROLS_ID")
Example
Say that you decide to create a HiddenField control in which to store the value from your database
ASPX (hidden field should be somewhere inside the gridview - right under Btnapptid should be fine)
<asp:HiddenField ID="hfMyControl" runat="server" Visible="False"
Value='<%# Bind("SOME_DB_COLUMN") %>'/>
VB (inside Staffgv_RowCommand())
Dim hfMyControl As HiddenField = _
DirectCast(Staffgv.Rows(index).FindControl("hfMyControl"), HiddenField)
Then simply use the value of hfMyControl
hfMyControl.Value
You could also repeat all this using multiple controls in order to potentially access multiple DB values stored in controls in the gridview.
I have a DataGrid on my webapge that looks like this:
<asp:datagrid id="dgCodes" runat="server" bodyHeight="300px" CssClass="tblScroll" Width="100%">
<Columns>
<asp:TemplateColumn ItemStyle-HorizontalAlign="Center" HeaderStyle-CssClass="clsGridHeaderText"
HeaderStyle-Wrap="False" HeaderStyle-Width="10%" ItemStyle-Width="10%">
<HeaderTemplate>
Select
</HeaderTemplate>
<ItemTemplate>
<INPUT type="radio" name="chkSelect" TabIndex="-1" value='<%# DataBinder.Eval(Container, "DataItem.Code") %>' onclick="mfpSetCode(this);" <%# mfpDisable(DataBinder.Eval(Container, "DataItem.Code")) %>>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
So there's 1 radio button column titled "Select", and then a few columns get added once the data is bound to the DataGrind.
When the user selects a radio button in this DataGrid, it's supposed to populate 2 child DataGrids, using a unique value in one of the bound columns.
I was able to set a SelectedIndexChanged event for the grid, hoping that'd catch the selection of the radio button column and then I could get the data that way, but it does not.
How can I get some data when a RB is selected like this?
Use an <asp:RadioButton> instead. This will give you the OnCheckChanged event.
<asp:RadioButton ID="rbSelect" runat="server"
Text='<%# DataBinder.Eval(Container, "DataItem.Code") %>'
OnCheckChanged="rbSelect_CheckChanged"
AutoPostBack="true" />
Then handle the event in your code behind.
Protected Sub rbSelect_CheckChanged(ByVal sender As Object, ByVal e As EventArgs)
{
}
I have a GridView that is made up of two database fields populated via a stored procedure and then three fields for user input (two checkbox controls and one textbox) when I click on the save button I can get the information from the three controls but nothing from the two that were populated via the database. How can I get the first two fields?
<asp:GridView ID="gvA1" runat="server" AutoGenerateColumns="false" DataKeyNames="CodeNo" AutoGenerateSelectButton="false" EnablePersistedSelection="True" Visible="false">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "CodeNo")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Wrap="true" ItemStyle-Width="400px" HeaderText="Violation">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "CodeViolationCited") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="A1Accordion_cbPool" runat="server" Text="Pool:" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="A1Accordion_cbSpa" runat="server" Text="Spa:" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Comments" Visible="true">
<ItemTemplate>
<asp:TextBox ID="A1Accordion_tb" runat="server" TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void SaveAndCollapseA1(object sender, EventArgs e)
{
//good stuff
CheckBox myCheckBox_1 = gvA1.Rows[0].FindControl("A1Accordion_cbPool") as CheckBox;
CheckBox myCheckBox_2 = gvA1.Rows[0].FindControl("A1Accordion_cbSpa") as CheckBox;
TextBox myTextBox = gvA1.Rows[0].FindControl("A1Accordion_tb") as TextBox;
//not so good stuff
String myString1 = gvA1.Rows[0].Cells[0].ToString();
String myString2 = gvA1.Rows[0].Cells[1].ToString();
}
I figured it out but I haven't been hear long enough to post the solution via the links but if you change the columns as so:
<asp:label ID="lblA1CodeNo" runat="server" text='<%# Eval("CodeNo") %>'></asp:label>
then the values are available...
Try:
<%# Bind("CodeViolationCited") %>
Instead of
<%#DataBinder.Eval(Container.DataItem, "CodeViolationCited") %>
Eval is one way, bind is two-way.
See Microsoft's documentation for data-binding expressions
It has been so long since I have coded a page in VB. For the life of me I just cannot remember how to do this.
I have a GridView on an ASP page. Each row has a comment ImageButton. I already have the gridview and text box wrapped in a UpdatePanel. The gridview shows all of the correct information. I just need to add some code to populate the text box with the comment when a user clicks on that row's ImageButton.
The comments are stored in SQL 2005 DB if that makes a difference. Should I shove the comments inside a hidden field of the gridview or is there a function that will allow me to query the db for that specific comment.
End goal would be to not refresh the page if possible.
Your help is greatly appreciated to help me get over this writer's block!
OK, you could do this either way, with a HiddenField or by looking up in the DB.
HiddenField
In the ItemTemplate that contains the ImageButton, add CommandName and CommandArgument attributes to the ImageButton, and a HiddenField that is bound to the comment field from the database:
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" CommandName="SelectComment" CommandArgument='<%# Container.DataItemIndex %>' />
<asp:HiddenField runat="server" id="CommentHiddenField" Value='<%# Eval("Comment") %>' />
</ItemTemplate>
</asp:TemplateField>
In the code-behind, add a method for handling the RowCommand event for the GridView:
Private Sub Gridview2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview2.RowCommand
Dim rowIndex As Integer
Dim commentHiddenField As HiddenField
If e.CommandName = "SelectComment" Then
rowIndex = Integer.Parse(e.CommandArgument.ToString)
commentHiddenField = DirectCast(Gridview1.Rows(rowIndex).Cells(5).FindControl("CommentHiddenField"), HiddenField)
txtComments.Text = commentHiddenField.Value
End If
End Sub
DB Lookup
Add the attributes to the ImageButton:
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" CommandName="SelectComment" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
In the code-behind, add a method for handling the RowCommand event for the GridView:
Private Sub Gridview2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview2.RowCommand
Dim rowIndex As Integer
Dim key As String
rowIndex = Integer.Parse(e.CommandArgument.ToString)
key = Gridview1.DataKeys(rowIndex).Value.ToString
txtComments.Text = GetCommentFromDB(key)
End Sub
Here is the markup...
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<tr class="dvrow" align="center">
<td style="text-align:left;" colspan="2">History<br />
<div id="div1" style="width:600px;">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
GridLines="None" DataKeyNames="RepIssueHistoryID"
DataSourceID="sqlIssueHistory" Width="600px" AllowSorting="True"
AllowPaging="True" CssClass="grid" RowStyle-Height="15px">
<PagerStyle CssClass="footer" />
<Columns>
<asp:TemplateField HeaderText="Mail">
<ItemTemplate>
<asp:CheckBox ID="chkMailComment" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RepIssueStatus" SortExpression="RepIssueStatus"
HeaderText="Status" ItemStyle-Width="120px" >
<ItemStyle Width="120px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="RepIssuePriority" SortExpression="RepIssuePriority"
HeaderText="Priority" ItemStyle-Width="100px" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="User" SortExpression="User" HeaderText="Rep"
ItemStyle-Width="180px" >
<ItemStyle Width="180px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DateUpdate" SortExpression="DateUpdate"
HeaderText="Date" ItemStyle-Width="200px" >
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachment">
<ItemTemplate>
<asp:ImageButton ID="btnAttachment" runat="server" ImageUrl="images/folder.gif" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No history currently exists.<br />
</EmptyDataTemplate>
<RowStyle Height="15px"></RowStyle>
<EmptyDataRowStyle CssClass="empty" />
</asp:GridView>
</div>
</td>
</tr>
<tr class="dvrow" align="center">
<td style="text-align:left;" colspan="2">Rep Comment<br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine"
Width="600px" Height="180px" ReadOnly="true" />
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
So the basic idea would be for someone to click on btnComment on whichever row and that comment would then show up in txtComment. Hope that explains it better.