Public Function GridView_RowUpdating(sender As Object, _
e As GridViewUpdateEventArgs) As Integer
Dim ID As Integer = GridView1.DataKeys(e.RowIndex).Value
Return ID
End Function
I need the id(datakey) for edit data from myGridview on another page. How can I do it?
chk this code will help you....
<asp:GridView ID="grdViewTracking" runat="server" AllowPaging="True" AllowSorting="true"
OnSorting="grdViewTracking_Sorting" AutoGenerateColumns="False" BorderColor="#E7E7E7"
BorderStyle="Solid" BorderWidth="1px" OnPageIndexChanging="grdViewTracking_PageIndexChanging"
CellPadding="1" ForeColor="#666666" PageSize="10" Width="100%">
<Columns>
<asp:TemplateField HeaderText="#" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<table>
<tr style="background-color: White">
<td style="padding-left: 5px;">
<%#DataBinder.Eval(Container.DataItem, "Number")%>
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Key" SortExpression="Key" ItemStyle-HorizontalAlign="Left">
<HeaderStyle HorizontalAlign="Left" CssClass="PaddingLeft5" />
<ItemTemplate>
<table>
<tr style="background-color: White">
<td style="padding-left: 5px">
***<asp:LinkButton ID="lnkkey" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Key")%>'></asp:LinkButton>***
<input type=hidden runat="server" id="hfid" value=' <%#DataBinder.Eval(Container.DataItem, "Appsettingid")%>' />
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle Width="15%" />
</asp:TemplateField>
below code to transfer control to second page i.e. edit page.....
protected void grdViewTracking_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
BusinessLogicPOS.AppSettingArgs ob = e.Row.DataItem as BusinessLogicPOS.AppSettingArgs;
LinkButton lnkkey = e.Row.FindControl("lnkkey") as LinkButton;
lnkkey.PostBackUrl = "AppSetting.aspx?AppSettingId=" + ob.AppSettingId.ToString();
}
Check reference:
example
The simplest way to do this will be like this.
At WebForm1 markup use either of these two methods
a. Use a asp:TemplateField
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="EditLink" runat="server"
NavigateUrl='<%# "~/WebForm2.aspx?id=" + Eval("ID") %>'
Text="Update" />
</ItemTemplate>
</asp:TemplateField>
b. Use a asp:HyperLinkField
<asp:HyperLinkField Text="Update"
DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="~\WebForm2.aspx?id={0}"
HeaderText="Action" />
And at WebForm2 code-behind do this
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Request.QueryString("id") IsNot Nothing Then
Dim passedID As String = Request.QueryString("id")
'populate the fields using .FirstOrDefault
Else
'no id passed. cannot process
End If
End If
End Sub
Related
struggling since morning. the scenario is as follow:
I have a ASP.NET web page having
two dropdownlist
two buttons
One GridView
Wants to fill gridview based on dropdownlist selected value
here is the .aspx code
<%# Page Title="" Language="VB" MasterPageFile="~/Admin/ADMIN.master" AutoEventWireup="false" CodeFile="EditSTUdetail.aspx.vb" Inherits="Admin_EditSTUdetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<style type="text/css">
.auto-style1
{
height: 42px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div align="center">
<fieldset>
<legend style="font-size: 16px;">SEARCH / EDIT / DELETE STUDENT RECORDS
</legend>
<div style="overflow: auto">
<div>
<asp:Label ID="lblMsg" runat="server" CssClass="lblresponse" />
<table style="margin: 3px auto 1px auto; height: 72px;">
<tr>
<td style="text-align: right;" class="auto-style2">Select Session/सत्र का चयन करें :
</td>
<td class="auto-style3">
<asp:DropDownList ID="ddlSession" runat="server" AppendDataBoundItems="True" Width="236px" Height="28px">
<asp:ListItem Text="--Select Session--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="ddlSession" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="text-align: right;" class="auto-style1">Select Course /कक्षा का चयन करें :
</td>
<td>
<asp:DropDownList ID="ddlCourse" runat="server" AppendDataBoundItems="true" Width="236px" Height="28px">
<asp:ListItem Text="--Select Course--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="ddlCourse" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="auto-style1"></td>
<td class="auto-style1">
<asp:Button ID="btnSearch" runat="server" Text="SEARCH" CssClass="button" OnClick="btnSearch_Click" Height="34px" Width="77px" /></td>
<td colspan="2" class="auto-style1">
<asp:Button ID="btnRefresh" runat="server" Text="REFRESH" CssClass="button" OnClick="btnRefresh_Click" Height="34px" Width="77px" /></td>
</tr>
</table>
</div>
</div>
<asp:GridView ID="GVdata" runat="server" Width="674px" CaptionAlign="Top"
AutoGenerateColumns="False" Height="100px" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" GridLines="Vertical"
EmptyDataText="There Are No Record Found" OnRowCancelingEdit="gvManageOrders_RowCancelingEdit"
OnRowDeleting="gvManageOrders_RowDeleting" OnRowEditing="gvManageOrders_RowEditing"
OnRowUpdating="gvManageOrders_RowUpdating">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Sr. No." ItemStyle-Width="20">
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit/Remove" ShowDeleteButton="True"
ShowEditButton="True" DeleteText="Remove" />
<asp:TemplateField HeaderText="Student ID" Visible="True">
<ItemTemplate>
<asp:Label ID="studentID" runat="server" Text='<%# Bind("studentID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Sname" runat="server" Text='<%# Bind("Sname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father's Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Fname" runat="server" Text='<%# Bind("Fname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle BackColor="#eeeeee" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px" Font-Size="Large" ForeColor="#851010"
HorizontalAlign="Center" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#851010" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#851010" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</fieldset>
</div>
</asp:Content>
and here is my vb code:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Net.Mail
Imports System.Data
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Partial Public Class Admin_EditSTUdetail
Inherits System.Web.UI.Page
Private myds As DataSet
Protected Sub LoadSession()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("select sessionID, session from tblcategories ORDER by session DESC", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlSession.DataTextField = ds.Tables(0).Columns("session").ToString()
' text field name of table dispalyed in dropdown
ddlSession.DataValueField = ds.Tables(0).Columns("sessionID").ToString()
' to retrive specific textfield name
ddlSession.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlSession.DataBind()
ddlSession.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub LoadCourse()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("SELECT DISTINCT course AS mycolumn FROM " _
& " tblsubjects where course is not null and " _
& "not course = '' order by mycolumn", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlCourse.DataTextField = ds.Tables(0).Columns("mycolumn").ToString()
' text field name of table dispalyed in dropdown
ddlCourse.DataValueField = ds.Tables(0).Columns("mycolumn").ToString()
' to retrive specific textfield name
ddlCourse.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlCourse.DataBind()
ddlCourse.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub fillgrid()
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
Dim cmd As New SqlCommand("SELECT StudentID,session,course,Sname,Fname FROM [tblstudetail] WHERE " _
& " [session] = '" + ddlSession.SelectedValue.ToString() + "' AND " _
& " [course] = '" + ddlCourse.SelectedValue.ToString() + "'", cn)
cn.Open()
Dim da As New SqlDataAdapter(cmd)
myds = New DataSet()
da.Fill(myds)
GVdata.DataSource = myds
GVdata.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadSession()
LoadCourse()
fillgrid()
End If
End Sub
Protected Sub gvManageOrders_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowEditing(sender As Object, e As GridViewEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not Page.IsPostBack Then
fillgrid()
End If
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
GVdata.DataSource = Nothing
End Sub
End Class
But it is not returning what i request.
Kindly HELP me out this....
PLease remove these lines ,
ddlSession.SelectedIndex = -1
ddlCourse.SelectedIndex = -1
from the end of the LoadCourse and LoadSession methods. These are resetting the dropdown values and causing issue.
The flow is messed up in your code. You are calling loadsession , loadcourses and fillgrid serially from the page load method. Think about it. When the code in fillgrid executes there is no selected value in the drop downs. Obviously no data is found and so the gridview is not visible.
The better way to handle is introduce two new methods like this,
Protected Sub ddlCourses_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlSession.SelectedIndexChanged
and
Protected Sub ddlAC3_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlCourse.SelectedIndexChanged
Inside these methods send out a call to fillgrid.
Also inside the fillgrid method first validate there is some value in both the ddlCourse and ddlSession dropdowns , then send out the database command.
First of all
ddlSession.SelectedValue.ToString()
become
ddlSession.SelectedValue
Then in Protected Sub btnSearch_Click remove
If Not Page.IsPostBack Then
Then
ddlCourse.SelectedIndex = -1
become
ddlCourse.ClearSelection();
Finally, are you sure there aren't NULL value in the database?
I have manage to merge the rows in my grid-view with the same values together as the example below shows.
Country----------Name-----------
USA-------------Chris------------
-------------------Jan------------Calculate
Africa------------Alta------------
-------------------Abri------------
China-----------Lee------------
The problem however is I want the display to look like this.
Country----------Name-----------Calculate
USA-------------Chris--------------Calculate
-------------------Jan----------------Calculate
Africa------------Alta----------------Calculate
-------------------Abri-----------------Calculate
China-----------Lee-----------------Calculate
The Calculate is a button.. Sorry I can't put in nice images I don't have enough rep yet to do so.
I have no idea how to fix this here is my grid-view.
<table>
<tr>
<td>
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" BorderColor="Black" BorderStyle="Solid" CssClass="grd" DataKeyNames="ID" DataSourceID="Datasource" EmptyDataText="There are no data records to display." PageSize="5"Width="900px">
<AlternatingRowStyle CssClass="grdalt" />
<Columns>
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-BorderStyle="Solid">
<ItemStyle BorderStyle="Solid" />
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-BorderStyle="Solid">
<ItemStyle BorderStyle="Solid" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdcalculate" runat="server" Text="Calculate" CommandArgument='<%# Eval("ID")%>'
CommandName="Calculate" Width="150px" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="160px" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="grdhead" />
<SelectedRowStyle BackColor="#80FFFF" />
</asp:GridView>
<asp:SqlDataSource ID="Datasource" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT ID,Country,Name From Table">
</asp:SqlDataSource>
</td>
</tr>
</table>
Here is my code behind.
Public Sub GridView_Row_Merger(gridView As GridView)
For rowIndex As Integer = gridView.Rows.Count - 2 To 0 Step -1
Dim currentRow As GridViewRow = gridView.Rows(rowIndex)
Dim previousRow As GridViewRow = gridView.Rows(rowIndex + 1)
For i As Integer = 0 To currentRow.Cells.Count - 1
If currentRow.Cells(i).Text = previousRow.Cells(i).Text Then
If previousRow.Cells(i).RowSpan < 2 Then
currentRow.Cells(i).RowSpan = 2
Else
currentRow.Cells(i).RowSpan = previousRow.Cells(i).RowSpan + 1
End If
previousRow.Cells(i).Visible = False
End If
Next
Next
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
Gridview1.DataBind()
GridView_Row_Merger(Gridview1)
End If
End Sub
If anyone can assist me please will be nice.
Hi guys I solved it in an easier way I think.
Here is my answer..
Gridview..
<table>
<tr>
<td>
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False"
BorderColor="Black" BorderStyle="Solid" CssClass="grd" DataKeyNames="ID"
DataSourceID="Datasource" EmptyDataText="There are no data records to display." PageSize="4"
Width="900px">
<AlternatingRowStyle CssClass="grdalt" />
<Columns>
<asp:TemplateField HeaderText="Country" Visible="True">
<ItemTemplate>
<asp:Label ID="Country" runat="server" Text='<%# Eval("Country")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-BorderStyle="Solid">
<ItemStyle BorderStyle="Solid" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdownvalues" runat="server" Text="Calculate" CommandArgument='<%# Eval("ID")%>'
CommandName="Target" Width="150px" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="160px" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="grdhead" />
<SelectedRowStyle BackColor="#80FFFF" />
</asp:GridView>
<asp:SqlDataSource ID="Datasource" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT ID,Country,Name From Table">
</asp:SqlDataSource>
</td>
</tr>
</table>
Here is my code Behind..
Private Sub Gridview1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim titleLabel As Label = e.Row.FindControl("Country")
Dim strval As String = CType(titleLabel, Label).Text
Dim title As String = ViewState("title")
If title = strval Then
titleLabel.Visible = False
titleLabel.Text = String.Empty
Else
title = strval
ViewState("title") = title
titleLabel.Visible = True
titleLabel.Text = "<br><b>" & title & "</b><br>"
End If
End If
End Sub
I would like to retrieve a row from the gridview by clicking on ImageButton (Booking):
here is the code of my grid view:
<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText=" Booking">
<ItemTemplate>
<asp:ImageButton ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" PostBackUrl="form.aspx"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Trade" HeaderText="Trade" SortExpression="Trade" />
<asp:BoundField DataField="CARRIER" HeaderText="CARRIER"
SortExpression="CARRIER" />
</Columns>
</asp:GridView>
The textbox of the form.aspx page that should be filed from the gridview row:
<asp:TextBox ID="trade" runat="server" CssClass="input , focus"></asp:TextBox>
<asp:TextBox ID="carrier" runat="server" CssClass="input , focus"></asp:TextBox>
Add GridView RowCommand event and command argument for image button where you can pass an id or something to determine the current row.
<asp:GridView onrowcommand="gvRowCommand" ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:ImageButton CommandArgument='<%# Eval("SomeId") %>' ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" />
</ItemTemplate>
C#
protected void gvRowCommand(object sender, GridViewCommandEventArgs e)
{
var someId = e.CommandArgument;
}
VB.Net
Protected Sub gvRowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
Dim someId As Integer = Convert.ToInt32(e.CommandArgument)
End Sub
You can refer msdn for more : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
I have a GridView,
without using SelectedIndexChanged, how can I retrieve the value of each row from GridView when click on each button in each row?
this is my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1" ShowHeader="False" AllowPaging="True" BorderColor="White"
CellPadding="6" GridLines="None" Height="100px" Width="800px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Card Name:
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
<br />
Cost :
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
<br />
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductImgID") %>'></asp:Label>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# Eval("ProductImgUrl", "images/{0}") %>' />
<br />
<asp:Button ID="btnAddProduct" runat="server" Text="Add" />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
One option can be to Bind the CommandArgument of the button to the ProductID
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%#Bind("ProductID")%>' />
and then in the RowCommand event retrieve the ProductID and extract the row from database
string prodID=(string)e.CommandArgument()
then using the ID retrieve the row from database.
To get a row value, you have to get the row Reference, After getting the row you can easily get to the specified column and can get the value
Lets Consider you have a "link button control" in a template field column. For the gridview you have to set Row Command Event, and also in the edit template of the column, set a command name for the link button also say "lnkTest"
In RowCommand Event you have to include the following section of code
if(e.CommandName.Equals("lnkTest")) // Checks that link button was clicked
{
GridViewRow grdRow = (((LinkButton)e.CommandSource).Container)
// This Will give you the reference of the Row in which the link button was clicked
int grdRowIndex = grdRow.RowIndex;
//This will give you the index of the row
var uniqueDataKeyValue = GridView1.DataKeys[grdRowIndex].Value;
//This will give you the DataKey Value for the Row in which the link Control was click
Hope the above code will help
Add CommandArgument='<%# Container.DataItemIndex %>' to your Add button
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%# Container.DataItemIndex %>'/>
To retrive Name, in gridview row command use this code
Dim gvr As GridViewRow = grvGRNCONs.Rows(e.CommandArgument)
Dim name As String = DirectCast(gvr.FindControl("Label1"), Label).Text
and so on..
<asp:GridView ID="grdResults" CssClass="CommonTable dataTable" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Sl#">
<ItemTemplate>
<asp:Label ID="lblSlno" Text='<%# Container.DataItemIndex+1 %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ControlStyle-Height="15px" ControlStyle-Width="15px">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" CssClass="PInfoTd" />
<ItemTemplate>
<asp:ImageButton ID="lknassesno" ToolTip="Edit Assessment" Width="50" CssClass="NewButton" ***CommandName="LINK"***
runat="server" ImageUrl="~/img/Edit.png" />
<asp:HiddenField ID="hidassesmentno" Value='<%# EVAL("PAN_CODE")%>' runat="server" />
<asp:HiddenField ID="hidPendStatus" Value='<%# EVAL("Pstatus")%>' runat="server" />
<asp:HiddenField ID="hidIPNO"Value='<%#EVAL("IP_NO")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**code behind**
Protected Sub grdResults_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdResults.RowCommand
If **e.CommandName = "LINK"** Then
Dim ctrl As Control = e.CommandSource
Dim grrow As GridViewRow = ctrl.Parent.NamingContainer
'Dim i As Integer = Convert.ToInt16(e.CommandArgument)
'Dim lknassesno As HiddenField = DirectCast(e.CommandSource, ImageButton)
Dim hidAssesmentNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidassesmentno"), HiddenField)
Dim lblstatus As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidPendStatus"), HiddenField)
Dim hidIpNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidIPNO"), HiddenField)
Dim Assno As String = hidAssesmentNo.Value
Dim Ipno As String = hidIpNo.Value
Dim st As String = ""
If lblstatus.Value = "Pending" Then
st = "E"`enter code here`
ElseIf lblstatus.Value = "Completed" Then
st = "V"
End If
Response.Redirect("Assessment.aspx?PAssNo=" & Assno & "&Mode=" & st & "&IPNO=" & Ipno & "")
End If
End Sub
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.