hi i have a gridview in my asp.net webpage that is bounded after a user selects 3 dropdown list.
dropdown list's auto postbacks are set true , now my problem is when i put a button , imagebutton or linkbutton in my gridview ItemTemplate the onclick event dosent fire !
here is my code
<asp:GridView ID="GridView1" runat="server" Width="90%" Height="100%" OnRowCommand="GridView1_RowCommand" OnPageIndexChanging="GridView1_PageIndexChanging" style="margin:20px; vertical-align:top;" PageSize="10" AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="WFStudentID" ShowHeader="true" BorderWidth="1px">
<Columns>
<asp:TemplateField ShowHeader="true">
<ItemTemplate >
<tr>
<td>
<asp:Label ID="Label1" ForeColor="Silver" Font-Size="Medium" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label2" runat="server" ForeColor="Silver" Font-Size="Medium" Text='<%# Bind("Family") %>'></asp:Label>
</td>
<td>
<asp:HyperLink ID="HyperLink1" ForeColor="Silver" Font-Size="Medium" Target="_blank" NavigateUrl='<%# Bind("WFStudentFilePath") %>' runat="server">دانلود</asp:HyperLink>
</td>
<td>
<asp:Label ID="Label7" runat="server" ForeColor="Silver" Font-Size="Medium" Text='<%# Bind("WFStudentDate") %>'></asp:Label>
</td>
<td>
<asp:Button ID="Deny" Text="deny" OnClick="Deny_Click1" runat="server" />
</td>
<td>
<asp:ImageButton ID="accept" OnClick="accept_Click" runat="server" />
</td>
<td>
<asp:TextBox ID="des" TextMode="MultiLine" Height="100px" Width="200px" runat="server"></asp:TextBox>
</td>
</tr>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Deny_Click1(object sender, EventArgs e)
{
Response.Redirect("home.aspx");
}
It is probably firing, but it will throw an exception (which your catch block ignores). The exception is because of this line:
LinkButton Link = (LinkButton)sender;
The sender is a Button, not a LinkButton, so the cast is not valid and an exception will be thrown.
you can check this::
http://www.dotnetbull.com/2013/05/how-to-handle-click-event-of-linkbutton.html
verify your code like this
Buttons inside GridView do not respond to direct events. They have to go through GridView's RowCommand event implementation. I've seen that you have implemented OnRowCommand="GridView1_RowCommand". So now you need make following change to image button:
<asp:ImageButton ID="accept" runat="server" CommandName="Accept" />
Now look for "Accept" command name in your GridView1_RowCommand event handler.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
// Your code goes here
}
}
I hope this helps.
Related
I am trying to use findcontrol TextBox in RowCommand of the gridview.
But Error Object reference not set to an instance of an object.
Help me please.
Design
<asp:GridView ID="gvMaster" runat="server" AllowPaging="true" AutoGenerateColumns="False" OnRowCommand="gvMaster_RowCommand" Width="100%">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="ibtnEdit" runat="server" CommandName="edit" ImageUrl="~/images/edit.gif" ToolTip="Insert/Edit" />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td nowrap="nowrap">
<asp:ImageButton ID="ibtnSave" runat="server" CommandName="update" ImageUrl="~/images/icon-floppy.gif" ToolTip="Save" />
</td>
<td nowrap="nowrap">
<asp:ImageButton ID="ibtnCancel" runat="server" CommandName="cancel" ImageUrl="~/images/icon-cancel.gif" ToolTip="Cancel" />
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="30px" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:Label ID="lblEffectiveDate" runat="server" Text='<%# String.Format("{0:dd/MM/yyyy}", Eval("eff_date")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td nowrap="nowrap">
<asp:TextBox ID="txtEffDate2" runat="server" MaxLength="10" Text='<%# String.Format("{0:dd/MM/yyyy}", Eval("eff_date")) %>'
Width="70px" Style="text-align: center"></asp:TextBox>
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code BeHind:
protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToUpper().Equals("SELECT"))
{
}
else if (e.CommandName.ToUpper().Equals("EDIT"))
{
string cmdNmEdit = e.CommandName;
object cmdSrcEdit = e.CommandSource;
GridViewRow gvMaster = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
TextBox txtEffDate2 = gvMaster.FindControl("MyTextBoxId") as TextBox;
txtEffDate2.Text = DateTime.Now.ToString("DD/MM/yyyy"); //<------ Error This Line
}
}
How can use FindControl in the OnRowCommand of GridView?
Thanks in advance. ;)
The CommandArgument contains the row-index by default. That's why this works:
protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridView grid = (GridView) sender;
GridViewRow row = grid.Rows[rowIndex];
// now you can use row.FindControl
}
I am having trouble determining where the bug is for this problem.
I have an ASP.NET Master.Page web application that has a Gridview. I am using the jquery-chosen plugin for a dropdown list in the EmptyDataTemplate (or FooterControl if there is data).
On initialization if there is no data for the grid, the dropdown is populated and displays correctly. If the grid has items in it and I delete all of them, so that there is no data, the dropdown does not display any data. The DataBound event is called and the DataTable has all of the correct data in it. It is bound to the dropdown. But do items appear in the list.
This is my markup:
<div id="DelegateGridWrapper">
<asp:GridView ID="DelegateInfoGridView" runat="server"
AutoGenerateColumns="false" Caption="Delegate Information"
CaptionAlign="Top" CssClass="grid" RowStyle-Wrap="true"
HorizontalAlign="Left" ShowFooter="true"
AllowPaging="true" PageSize="5" ShowHeaderWhenEmpty="false" onrowediting="DelegateInfoGridView_RowEditing"
onrowcancelingedit="DelegateInfoGridView_RowCancelingEdit" onrowdeleting="DelegateInfoGridView_RowDeleting"
onrowupdating="DelegateInfoGridView_RowUpdating"
ondatabound="DelegateInfoGridView_DataBound"
onrowcommand="DelegateInfoGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Recipient ID">
<ItemTemplate>
<asp:Label ID="deligvLblRecipientID" runat="server" Text='<%# Bind("RecipientID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delegate" ItemStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="deligvLblRecipientName" runat="server" Text='<%# Bind("RecipientName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
data-placeholder="Choose delegate…" class="chosen-single">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:Label ID="deligvLblActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="deligvDDLActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="deligvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="gridActionbutton">
</asp:Button>
<asp:Button ID="deligvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete" ClientIDMode="Static"
Text="Delete" CssClass="gridActionbutton" OnClientClick="return confirm('Are you sure you want to delete this Delegate Information?')" >
</asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="deligvUpdateButton" runat="server" CausesValidation="False" CommandName="Update"
Text="Update" CssClass="gridActionbutton"></asp:Button>
<asp:Button ID="deligvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel" CssClass="gridActionbutton"></asp:Button>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="deligvAddButton" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<th>Recipient ID</th>
<th>Delegate</th>
<th>Active</th>
<th>Action</th>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
No Delegates were found for you. Delegates can be added by clicking the 'Add Delegate' Button.
</td>
</tr>
<tr>
<td></td>
<td>
<asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
data-placeholder="Choose delegate…" class="chosen-single">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:Button ID="deligvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
This is my DataBound event:
protected void DelegateInfoGridView_DataBound(object sender, EventArgs e)
{
try
{
m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Get the Footer controls that have the new entry data
Control tFooterControls = getFooterControls(DelegateInfoGridView);
DropDownList ddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
ddlRecipientNames.DataSource = tdtAllDelegates;
ddlRecipientNames.DataTextField = "RecipientName";
ddlRecipientNames.DataValueField = "RecipientID";
ddlRecipientNames.DataBind();
ddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
}
catch (Exception ex)
{
//TO DO: Response.Redirect("~/Error.aspx");
}
}
Why won't the dropdown display the items after all items are deleted but will correctly display if initially there are no items in the gridview to display?
I tried triggering an update for the chosen dropdown but that is called initially, before the data is retrieved.
I don't know if there is a bug in the code-behind or do I need to add something in the javascript.
Thanks.
UPDATE
The problem is not with the chosen plugin. I removed the attribute from the DropDown list that changes it to a 'chosen' style and the problem still exists. So the asp:DropDownList will not populate after the user deletes all of the items in the grid. But if the grid is initialized with no items, the DropDown is correctly populated.
UPDATE
I got a suggestion to use the 'RowDeleted' event to bind the dropdown. However, the event is not firing. I added the event to the markup:
onrowdeleted="DelegateInfoGridView_RowDeleted"
This is the event that is never called:
protected void DelegateInfoGridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
try
{
m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Get the Footer controls that have the new entry data
Control tFooterControls = getFooterControls(DelegateInfoGridView);
DropDownList tddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
tddlRecipientNames.DataSource = tdtAllDelegates;
tddlRecipientNames.DataTextField = "RecipientName";
tddlRecipientNames.DataValueField = "RecipientID";
tddlRecipientNames.DataBind();
tddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
}
catch (Exception ex)
{
//TO DO: Response.Redirect("~/Error.aspx");
}
}
What is different about the RowDeleted event that it will not fire?
The problem was that I was checking if the FooterControl was null. If it was, I got the EmptyTemplateData control. When you delete all of the rows, the FooterControl is not null, but it needs to get the EmptyTemplateData control.
So, I changed the logic to check for Grid Row Count > 0 instead of a null FooterControl.
That fixed the problem..
Soo I'm trying to filter my gridview with textboxes in the header. I created a textchanged method for every textbox. Now I want to filter the gridview and bind the filtered data. For some reason the datasource is null once it hits the textchanged method. See my code below:
<asp:GridView ID="GridView_Imported" runat="server" CssClass="GridView-Upload" Width="100%" OnRowDataBound="GridView_Imported_RowDataBound" HorizontalAlign="Center" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" CssClass="checkAll" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" CssClass="chkCtrl" onclick="Check_Click(this)" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="filter">
<HeaderTemplate>
<asp:Label ID="lbArticleName" runat="server" Text="Article-Name:" CssClass="Article-Name-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterArticleName" runat="server" placeholder="Filter..." OnTextChanged="tbFilterArticleName_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="ArticleNameText" runat="server" Text='<%# Eval("Article-Name") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbArticle" runat="server" Text="Article:" CssClass="Article-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterArticle" runat="server" placeholder="Filter..." OnTextChanged="tbFilterArticle_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbArticleText" runat="server" Text='<%# Eval("Article") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbWarehouse" runat="server" Text="Warehouse:" CssClass="Warehouse-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterWarehouse" runat="server" placeholder="Filter..." OnTextChanged="tbFilterWarehouse_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbWarehouseText" runat="server" Text='<%# Eval("Warehouse") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbLocation" runat="server" Text="Location:" CssClass="Location-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterLocation" runat="server" placeholder="Filter..." OnTextChanged="tbFilterLocation_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbLocationText" runat="server" Text='<%# Eval("Location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
protected void tbFilterArticleName_TextChanged(object sender, EventArgs e)
{
var tb = (TextBox) sender as TextBox;
GridView_Imported.DataSource = (Session["dataSource"] as DataTable).DefaultView.RowFilter = string.Format("Article-Name LIKE '%{0}%'", tb.Text.Trim());
GridView_Imported.DataBind();
}
What I'm missing?
There are two errors in your code.
First put brackets for column name Article-Name as [Article-Name].
Second the way you assigning datasource to gridview. See the correct way below.
var dt = (Session["dataSource"] as DataTable);
dt.DefaultView.RowFilter = string.Format("[Article-Name] LIKE '%{0}%'", tb.Text.Trim());
GridView_Imported.DataSource = dt;
GridView_Imported.DataBind();
Use http://www.datatables.net/
It provides data filtering, sorting, paging etc.
Just place a html table header above your gridview with some id
<HeaderTemplate>
<table id="tblData" border="0" cellpadding="5" cellspacing="1" width="100%">
<thead>
<th align="center" width="3%">S.No.
</th>
<th align="center" width="10%">RFQ ID
</th>
</thead>
</HeaderTemplate>
Add add jquery script
$(document).ready(function () {
$('#tblData').DataTable();
});
First, in RowDataBound event of your gridview(to find your textbox):
System.Web.UI.WebControls.TextBox tbFilterArticle;
protected void GridView_Imported_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView_Imported.HeaderRow != null)
{
tbFilterArticle = (System.Web.UI.WebControls.TextBox)GridView_Imported.HeaderRow.FindControl("tbSearchUser");
}
}
After that, to use it's value(anywhere you want, i used it into a button click event):
string article = tbFilterArticle.Text;
I have a drop down list. On changing the index of the dropdownlist , I populate an asp.net gridview.
I have a requirement where the user should be able to remove individual rows of the gridview on the screen .
At the end of each row, I intend to have a remove button. On clicking the button the row should
disappear . But this should be only on the screen. There should be no changes done in the database.
I have my code below right now :
aspx
<table>
<tr>
<td>
<div>
<asp:Label ID="lblClient" runat="server" Text="Client :" CssClass="label" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="ddlClient" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="ddlClient_SelectedIndexChanged">
<asp:ListItem Text="ALL" Value="0"></asp:ListItem>
</asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvMainLog" runat="server" Visible="true" AllowSorting="True" AutoGenerateColumns="False"AllowPaging="true">
<Columns>
<asp:BoundField DataField="Instruction" HeaderText="Instruction" />
<asp:BoundField DataField="ProviderId" HeaderText="Id" />
</Columns>
</asp:GridView>
<div>
<asp:TextBox ID="txtEditMin" runat="server"></asp:TextBox>
</div>
</td>
</tr>
</table>
aspx.cs
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
gvMainLog.DataSource = GetSetupUtility(1);
gvMainLog.DataBind();
}
In the GridView add the remove command like this
<Columns>
<asp:BoundField DataField="Instruction" HeaderText="Instruction" />
<asp:BoundField DataField="ProviderId" HeaderText="Id" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Remove"
Text="Remove" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
In the action of the remove button use the DeleteRow method
void gvMainLog_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Remove")
{
var id = Int32.Parse(e.CommandArgument);
gvMainLog.DeleteRow(id);
}
}
You need somthing like this:
Use TemplateField in gridview.
<script>
function deleteRow(rowId) {
$("#" + rowId).remove();
}
</script>
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div id='<%# "myRow" + Container.DataItemIndex %>'> contents <img src="deleteImageUrl" onclick='<%# "deleteRow(\"myRow" + Container.DataItemIndex+"\")" %>'/> </div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using a grid in which inside the item template(the first one in which radio button is there). i use link button instead of radiobutton ,when i click on it iam able to edit as the textbox appears, but if i use the radio button,that editing option is not coming;
aspx:
<div id="loginblock">
<table>
<tr>
<td>UserName:</td>
<td>
<asp:TextBox ID="username" runat="server" onBlur="txtvalidation();" AutoPostBack="true"></asp:TextBox>
</td>
<td>
<div id="warning" style="color:aqua;width:100px" runat="server">
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="PlS Enter Password" ControlToValidate="pwd"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="pwd" runat="server" TextMode="Password" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Button" />
</td>
</tr>
<tr>
<asp:GridView ID="grd" runat="server" OnRowEditing="selectrd_CheckedChanged" AutoGenerateColumns="false" DataKeyNames="userid">
<Columns>
<asp:TemplateField HeaderText="edition">
<ItemTemplate>
<asp:RadioButton ID="rdnselect" runat="server" CommndName="edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ids" DataField="userid" />
<asp:TemplateField HeaderText="password">
<ItemTemplate>
<%# Eval("pwd") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="edits" runat="server" Text='<%# Eval("pwd") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
cs:
protected void selectrd_CheckedChanged(object sender, GridViewEditEventArgs e)
{
grd.SelectedIndex = e.NewEditIndex;
ldgrid();
}
Here if we remove the radiobutton and insert link button,onclick of the link button we can edit the values,pls say me how to do the same operation with the radio button.