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.
Related
Hi guys,
I am not a developer but I always try my best to manage my page coding by myself before bothering anyone and by checking many examples and apply them to my web application, but this time I really surrendered and had to ask.
I have a Gridview where I will be using to update one field which is CHECKBOX.
The gridview has a checkbox control where it's checked attribute need to be True or False based on the Database value.
Values are 1 and 2 only
I wrote the below code to catch the cell label and change the checkbox attribute but it didn't work
Protected Sub Refill_checkbox(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer
For i = 0 To dg.Rows.Count - 1
Dim Test As String = CType(dg.Rows(i).Cells(3).FindControl("Att_Type"), Label).Text
If CType(dg.Rows(i).Cells(4).FindControl("Att_Type"), Label).Text = 1 Then
CType(dg.Rows(i).Cells(6).FindControl("CheckBox_Attendance"), CheckBox).Checked = True
Else
CType(dg.Rows(i).Cells(6).FindControl("CheckBox_Attendance"), CheckBox).Checked = False
End If
Response.Write(Test)
Next
End Sub
Unfortunately it even did not write the Test Variable to find if it catches the label from the gridview or not.
My Gridview is as following:
<asp:GridView ID="dg" runat="server" BorderColor="#CCCCCC" BorderStyle="None" AutoGenerateColumns="False"
BorderWidth="1px" CellPadding="4"
EnableModelValidation="True" ForeColor="Black" GridLines="Horizontal"
Width="99%" AllowPaging="True" PageSize="500" DataSourceID="SqlDataSource_BCS" >
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<%#Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Att_ID" HeaderText="Att_ID"
SortExpression="Att_ID" />
<asp:BoundField DataField="Emp_FullName" HeaderText="Emp_FullName"
SortExpression="Emp_FullName" />
<asp:BoundField DataField="Att_Desc" HeaderText="Att_Desc"
SortExpression="Att_Desc" />
<asp:BoundField DataField="Att_Type" HeaderText="Att_Type"
SortExpression="Att_Type" />
<asp:BoundField DataField="Att_Date" HeaderText="Att_Date"
SortExpression="Att_Date" />
<asp:templatefield HeaderText="Attendance" >
<itemtemplate >
<asp:CheckBox ID="CheckBox_Attendance" runat="server" />
</itemtemplate>
<itemstyle horizontalalign="left" />
</asp:templatefield>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="White" Font-Bold="True" BorderWidth="0px"/>
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BorderStyle="None" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
</asp:GridView>
I have no idea what is the correct way to do this.
Thanks in advance
You can bind your checkbox directly to the field like so...
<asp:CheckBox ID="CheckBox_Attendance" runat="server" Checked='<%# Eval("Att_type").ToString() = "1" %>' />
Otherwise, handle it directly on your gridview rowdatabound event:
Put the following on your gridview:
<asp:GridView ... OnRowDatabound="dg_RowDataBound">
Change your TemplateField to look like this:
<asp:TemplateField HeaderText="Attendance">
<ItemTemplate>
<asp:HiddenField id="hfType" Value='<%# Eval("Att_Type") %>' />
<asp:CheckBox ID="CheckBox_Attendance" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="left" />
</asp:TemplateField>
In your code behind
Protected Sub dg_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim cbAttendance As Checkbox = e.Row.FindControl("CheckBox_Attendance")
Dim hfType as Hiddenfield = e.Row.FindControl("hfType")
If hfType.Value = "1" Then
cbAttendance.Checked = True
End Sub
Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.
After clicking the edit linkbutton of my gridview, I show the data on different text boxes which are not inside the gridview. I have a "Reset" button which i want to use to get back to the original values. But I am having problem to access those gridview data inside the button click handler and reset it.I tried using DirectCast() but its showing System.NullReferenceException.
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" DataKeyNames="id">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" CausesValidation="false" CommandName="editRecord" Text="EDIT" CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
<ItemTemplate>
<asp:Label ID="lblRecordID" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HANGER">
<ItemTemplate>
<asp:Label ID="lblHANGER" runat="server" Text='<%# Bind("HANGER") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
The backend vb.net code is-
Protected Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnReset.Click
Dim vID As Label = DirectCast(GridView3.SelectedRow.FindControl("lblRecordID"), Label)
Dim vHanger As Label = DirectCast(GridView3.SelectedRow.FindControl("lblRecordID"), Label)
txtID.Text.Text = vID.Text()
ddlHanger.SelectedValue = vHanger.Text 'dropdown list that's why selectedValue used
End Sub
I have copied the portion of the code cause the gridview has lot more rows. I would appreciate if anyone please show me a solution.Thanks in advance.
First remove the following:
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" CausesValidation="false"
CommandName="editRecord" Text="EDIT"
CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
And add:
<asp:CommandField ButtonType="Button" ShowSelectButton="True" SelectText="EDIT" />
That markup will allow your GridView to have an EDIT button which will switch the current selected row index correctly. System.NullReferenceException error you are recieving could be because the GridView3.SelectedRow is NULL/EMPTY, which also means GridView3 currently has NO selected index.
To make sure that GrieView3 indeed selected a ROW, you can add: the following right AFTER the
<SelectedRowStyle BackColor="Black" BorderColor="White" BorderStyle="Dotted"
BorderWidth="3px" ForeColor="White" />
right after
</Columns>
So your final GridView3 markup should look like:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" DataKeyNames="id">
<Columns>
<asp:CommandField ButtonType="Button" ShowSelectButton="True"
SelectText="EDIT" />
<asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
<ItemTemplate>
<asp:Label ID="lblRecordID" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HANGER">
<ItemTemplate>
<asp:Label ID="lblHANGER" runat="server" Text='<%# Bind("HANGER") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle BackColor="Black" BorderColor="White" BorderStyle="Dotted"
BorderWidth="3px" ForeColor="White" />
</asp:GridView>
Then you can also use TryCast too, like so:
Protected Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnReset.Click
Dim vID As String = TryCast(GridView3.SelectedRow.FindControl("lblRecordID"), Label).Text
Dim vHanger As String = TryCast(GridView3.SelectedRow.FindControl("lblRecordID"), Label).Text
txtID.Text.Text = vID
ddlHanger.SelectedValue = vHanger
End Sub
Currently I am making a webapp in asp.net. Normally I use a sqlDataSource and enable paging and deleting etc, but I am not able to do that in this case.
I made a GridView and it shows the data perfectly, how ever my RowDelete event doesn't fire
Code GridView: ( only relevant code )
<asp:GridView ID="GridView1"
runat="server"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField
HeaderStyle-CssClass="head"
ItemStyle-CssClass="items"
HeaderText="Klant">
<ControlStyle ForeColor="#333333" />
<HeaderStyle CssClass="head"></HeaderStyle>
<ItemStyle CssClass="items" Font-Bold="False" ForeColor="#494C50" ></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="klant" runat="server"
Text='<%#Eval("Bedrijf") %>'
PostBackUrl='<%# "klant_wijzigen.aspx?Klant_ID="+Eval("Klant_ID").ToString()%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField
HeaderStyle-CssClass="head"
ItemStyle-CssClass="items"
HeaderText="Categorie">
<ItemTemplate>
<asp:LinkButton ID="categorie" runat="server"
Text='<%#Eval("Categorie") %>'
PostBackUrl='<%# "cat_wijzigen.aspx?Cat_ID="+Eval("Cat_ID").ToString()%>'>
</asp:LinkButton>
</ItemTemplate>
<ControlStyle ForeColor="#333333" />
<HeaderStyle CssClass="head"></HeaderStyle>
<ItemStyle CssClass="items" Font-Bold="false" ></ItemStyle>
</asp:TemplateField>
<asp:BoundField
DataField="Website"
headertext="Website"
HeaderStyle-CssClass="head"
ItemStyle-CssClass="items">
<HeaderStyle CssClass="head"></HeaderStyle>
<ItemStyle CssClass="items"></ItemStyle>
</asp:BoundField>
<asp:BoundField
HeaderStyle-CssClass="head"
DataField="Titel"
headertext="Titel"
ItemStyle-CssClass="items"
>
<HeaderStyle CssClass="head"></HeaderStyle>
<ItemStyle CssClass="items"></ItemStyle>
</asp:BoundField>
<asp:TemplateField
HeaderStyle-CssClass="head2"
ItemStyle-CssClass="items2">
<ItemTemplate>
<asp:Button ID="LinkButton1"
runat="server"
CausesValidation="False"
CommandName="Delete" Text="Delete"
CssClass="verwijder"
OnClientClick="return confirm
('Weet je zeker dat je het project wilt verwijderen?')">
</asp:Button>
<asp:Button ID="project" runat="server"
Text="Details"
CssClass="details"
PostBackUrl='<%#"Details.aspx?ID="+Eval("ID").ToString()%>'
/>
</ItemTemplate>
<HeaderStyle CssClass="head2"></HeaderStyle>
<ItemStyle CssClass="items2"></ItemStyle>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="head"></HeaderStyle>
<AlternatingRowStyle BackColor="#e1e3e9" />
</asp:GridView>
As you can see they are all bounded. The delete button is a LinkButtton
And this is my script:
Protected Sub Gridview1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
GridView1.DeleteRow(e.RowIndex)
GridView1.DataBind()
End Sub
I bind my GridView like this: I have made 2 seperate SqlDataSources with 2 different Select Queries. Based on on the SelectedValue of my dropdownlist selects the SqlDataSource:
Code
Public Sub Wop() 'Here I set the IF statement.
If DropDownList1.SelectedValue = 0 Then
GridView1.DataSource = SqlDataSource4()
Else
GridView1.DataSource = SqlDataSource2()
End If
GridView1.DataBind()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Wop() `Here is were I call the IF statement.
End Sub
Any clue would be appreciated.
NOTE
I must say I am not writing in C#!
You look like you're calling DeleteRow from within your RowDeleting event. That doesn't make any sense since I would imagine that RowDeleting is not raised until DeleteRow is called.
Edit:
From MSDN:
Use the DeleteRow method to programmatically delete the record at the
specified index from the data source. This method is commonly used
when you need to delete a record from outside of the GridView control,
such as from a different control on the page. Calling this method also
raises the RowDeleted and RowDeleting events.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.deleterow.aspx
I am trying to hide/display a linkbutton in my gridview based on wether not the row in the Gridview is part of my shopping cart.
This is the gridview
<asp:GridView ID="productListTable" runat="server" DataSourceID="srcProductListPerCustomer" AutoGenerateColumns="False" AlternatingRowStyle-CssClass="tr_dark" HeaderStyle-CssClass="header_req" BorderWidth="0px" GridLines="None" AllowPaging="true" PageSize="25" EmptyDataText="No records." AllowSorting="false" Width="100%" DataKeyNames="product_ID_key" OnRowDataBound="productListTable_RowDataBound" OnRowCommand="productListTable_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="Product Name" HeaderStyle-Width="250px" SortExpression="productName" ItemStyle-CssClass="product_name" >
<ItemTemplate>
<asp:Label ID="ProductNameField" runat="server" Text='<%# Eval("productName").ToString() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantity" Columns="5"></asp:TextBox><br />
<asp:LinkButton runat="server" ID="btnRemove" Text="Remove" CommandName="Remove" CommandArgument='<%# Eval("product_ID_key") %>' style="font-size:12px;" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="header_req" />
<AlternatingRowStyle CssClass="tr_dark" />
<PagerStyle CssClass="pagination" />
<PagerSettings PageButtonCount="3" FirstPageText="First" LastPageText="Last" NextPageText="Next" PreviousPageText="Previous" Mode="NumericFirstLast" />
</asp:GridView>
The way I am trying to do this at the moment is by row data bound
Protected Sub productListTable_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles productListTable.RowDataBound
' If we are binding the footer row, let's add in our total
If e.Row.RowType = DataControlRowType.DataRow Then
'e.Row.Cells(6).Text = "Total Price: " & ShoppingCart.Instance.GetSubTotal().ToString("C")
Dim productId = Convert.ToInt32(productListTable.DataKeys(e.Row.RowIndex).Value)
Dim txtQuantity As TextBox = CType(e.Row.Cells(1).FindControl("txtQuantity"), TextBox)
Dim removeButton As LinkButton = CType(e.Row.Cells(1).FindControl("btnRemove"), LinkButton)
Dim updatedItem = New CartItem(productId)
For Each item As CartItem In ShoppingCart.Instance.Items
If item.Equals(updatedItem) Then
txtQuantity.Text = item.Quantity
removeButton.Visible = True
End If
Next
End If
End Sub
And it works fine, but not at the initial refresh of the page when adding a new product but only after a hard refresh I see the button appear. Do I need to perform this check in a different lifecycle or gridview event so i can see the update immediately ?