i am using asp.net for my web application when i click on checkbox inside gridview and after that i check its value on button click it does not show me the exact value
here is asp code
<asp:GridView ID="dgvMenu" runat="server" Width="100%" CssClass="grid" GridLines="None"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
View
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="View" runat="server" Checked="<%#Bind('View') %>" />
</ItemTemplate>
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Menu" HeaderText="Menu Name">
<HeaderStyle HorizontalAlign="Left" CssClass="firstcol" />
<ItemStyle CssClass="firstcol" />
</asp:BoundField>
</Columns>
</asp:GridView>
and here is its vb version to get its value on button click version
For Each item As GridViewRow In dgvMenu.Rows
Dim MenuName As String = item.Cells.Item(1).Text
Dim chkView As CheckBox = DirectCast(item.FindControl("View"), CheckBox)
Next
i want to check its value whether its checked or unchecked so that i can process its value
I assume that your binding your GridView even on postbacks. You should only bind it if not PageIsPostback.
Put this into Page_Load:
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' following function loads data and binds it to the GridView '
BindGrid()
End If
End Sub
If you DataBind the Grid on every postback, ViewState cannot be reloaded, hence all changed values are lost and events will not be triggered correctly.
Related
I have a gridview with 100 Textboxes one below the other. I want to validate it as Atleast One textbox should be filled, otherwise Save button should not work and Ask for user to enter atleast one textbox. Is there any ways to do this?In my case, Gridview Textboxes Have same id as 'txtempcode'.
I'm using vb.net with SQl database as backend.
Here is my Design code
<asp:GridView ID="GridView2" runat="server" style="margin-left: 23px" Width="420px" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField Headertext="Sr No." DataField="Row_No" />
<asp:TemplateField HeaderText="Employee Code">
<ItemTemplate>
<asp:TextBox ID="TxtEmpcode" runat="server" OnTextChanged="TxtId_TextChanged" AutoPostBack ="true" ></asp:TextBox>
</Columns>
</asp:GridView>
In your Save button's click event:
Dim bValueFound as Boolean = False
for each i as listitem in GridView2.items
try
if DirectCast(i.findControl("TxtEmpcode"), TextBox).text > "" then
bValueFound = True
exit for
end if
catch
'Hopfully just Header
end try
next
If bValueFound then
'Do Save Button Tasks
else
'Remind user to fill something in?
End If
You may want to do more than just ...text > "" but I'll leave that up to you.
I created a simple Grid view with Multiple columns and add a button so when clicked pass the values of the row to a different webform but button on click not firing. I use the example code from the link
: http://msdn.microsoft.com/en-us/library/bb907626(v=vs.100).aspx
And this is my code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False">
<Columns>
<%--<asp:HyperLinkField HeaderText="Edit" NavigateUrl="FormReport2.aspx"
Text="Edit" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fldEmployeeID" HeaderText="EmployeeID"
SortExpression="fldEmployeeID" />
<asp:BoundField DataField="fldAbsentDate" HeaderText="AbsentDate"
SortExpression="fldAbsentDate" />
<asp:BoundField DataField="fldAbsentCode" HeaderText="AbsentCode"
SortExpression="fldAbsentCode" />
<asp:BoundField DataField="fldRuleViolationWarningType"
HeaderText="Rule Violation Warning Type"
SortExpression="fldRuleViolationWarningType" />
<asp:BoundField DataField="fldRuleViolationIssueDate"
HeaderText="Rule Violation Issue Date"
SortExpression="fldRuleViolationIssueDate" />
<asp:BoundField DataField="fldLOAEndDate" HeaderText="LOA End Date"
SortExpression="fldLOAEndDate" />
</Columns>
</asp:GridView>
code behind
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
Any help would be very appreciated. And also what would be the best way to pass the values from the row to a different web form from the code behind?
You forgot to sing up for the event. See the last line here:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand">
Hi all I have a simpe ASP button inside a grid. But the onclick event doesn't seem to fire. Where did I go wrong?
Here's the first line of my aspx page.
<%# Page Title="Trainer Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeFile="TrainerData.aspx.vb" Inherits="TrainerData"%>
And the button inside my gridview..
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" OnClientClick="btnExecutiveGenerate_Click" />
</ItemTemplate>
</asp:TemplateField>
P.S. I tried even onclick but it doesn't work either.
EDIT: My code for server side.
Protected Sub btnExecutiveGenerate_Click(sender As Object, e As EventArgs)
Dim gvrow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim lblSchoolId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblSchoolMasterID")
Dim lblFacultyId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblFacultyMasterID")
Dim btnExecutiveGenerate As System.Web.UI.WebControls.Button = gvrow.FindControl("btnExecutiveGenerate")
PDF_Creation_Executive(Val(lblSchoolId.Text), Val(lblFacultyId.Text))
End Sub
Use Command Argumnet,
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
add code page side
Protected Sub GridView1_RowCommand(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
You need to handle the button click event of Gridview in RowCommand event
NOTE: Please see the CommandName & CommandArgument properties added to the button.
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" OnRowCommand="gvExecSummary_RowCommand" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" CommandName="GenerateExecutive" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
And and RowCommand event will be..
protected void gvExecSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GenerateExecutive")
{
// button click code goes here
}
}
change OnClientClick event to OnClick if btnExecutiveGenerate_Click is vb.net event handler
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate"
OnClick="btnExecutiveGenerate_Click"/>
OnClientClick event use to execute client-side script, if you have given OnClientClick event with OnClick event, then if OnClientClick return true only it will call OnClick event.
so make sure you are returning true or false from OnClientClick event if you using it.
note that if you are loading data in page laod, do as below
Sub Page_Load
If Not IsPostBack
LoadGridViewData()
End If
End Sub
This may help someone, but I was experiencing edit buttons not firing the event within rows (and not footer).
The cause was a gridview containing a label, which had the same ID as one elsewhere on the page.
Seemingly this did not cause problems for the footer row, which did not contain any such labels.
I hope this helps someone.
I have a gridview with a button, and when the button is clicked, it fires a rowcommand procedure and adds a new row to the database. Everything works fine until I add a databound drop down list to the gridview.
With a databound dropdown list, the page loads fine, but when I click the button the error shows as "Internet Explorer cannot display the webpage". here is my code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
DataSourceID="SqlDataSource1">
<Columns>
<asp:ButtonField CommandName="insertNew"
Text="Button" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnAdd" runat="server" CommandName="insertNew"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField></asp:TemplateField>
</Columns>
</asp:GridView>
And here is my code behind that runs when the button is pressed;
Protected Sub GridView1_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "insertNew") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
MsgBox(index)
End If
End Sub
I just had to put this into the system.web web.config file
<httpRuntime maxRequestLength="32768" />
The problem is in the MsgBox line. MsgBox(index) is not supported in web applications.
Please remove MsgBox(index), and the issue will be fixed, because that feature is only supported in Windows Applications.
I have a Checkbox Control (column) in a header template field, for a Gridview control. On page load the gridview reads data from the server for each row. What I want is, when the header Checkbox control is checked, it updates the each row to either true or false (checked or unchecked) based on the checked state of the header column. The thing is after its checked, the header Checkbox it doesn't keep the checked state, so if I checked it, after posting the data back to the server it defaults to unchecked, I want it to keep it state, so I can uncheck it and save back to the database.
Here is the Code from the my .ASPX page
<asp:GridView ID="CategoriesGridView" runat="server" AutoGenerateColumns="false" EmptyDataText="No files Uploaded" BorderWidth="1px" BackColor="White"
AllowPaging="False" CellPadding="3" BorderStyle="None" BorderColor="#CCCCCC" Font-Names="Arial"
DataKeyNames="ID">
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<PagerStyle ForeColor="#000066" HorizontalAlign="Left"
BackColor="White"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#006699"></HeaderStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" Text="Show Discount" ItemStyle-Width="110" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkShowDiscountImage" runat="server" Checked='<%# Eval("ShowDiscountImage")%>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" />
</Columns>
<SelectedRowStyle ForeColor="White" Font-Bold="True"
BackColor="#669999"></SelectedRowStyle>
<RowStyle ForeColor="#000066"></RowStyle>
And here is the code form the code behind for the checkbox
Protected Sub chkAll_CheckedChanged(sender As Object, e As EventArgs)
Dim ChkBoxHeader As CheckBox = CType(CategoriesGridView.HeaderRow.FindControl("chkAll"), CheckBox)
'Enumerate each GridViewRow
For Each gvr As GridViewRow In CategoriesGridView.Rows
'Programmatically access the CheckBox from the TemplateField
Dim cb As CheckBox = CType(gvr.FindControl("chkShowDiscountImage"), CheckBox)
If ChkBoxHeader.Checked = True Then
cb.Checked = True
Else
cb.Checked = False
End If
Next
Save()
End Sub
Protected Sub Save()
Dim result As Boolean = False
For Each row As GridViewRow In CategoriesGridView.Rows
' Get the Id from the DataKey property.
Dim cId As Integer = Convert.ToInt32(CategoriesGridView.DataKeys(row.RowIndex).Values(0))
'Get the checked value of the CheckBox
Dim showDiscountImage As Boolean = TryCast(row.FindControl("chkShowDiscountImage"), CheckBox).Checked
result = CatalogServices.Categories.UpdateCategory(cId, showDiscountImage)
Next
If result = True Then
PopulateGridView()
Else
'ToDo Display Error of some sort
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Alert", "alert('There was a problem updating the database')", True)
End If
End Sub
Instead of using Page_Load use the Page_Init event.