I want to show "Delete" link in GridView to registred users, therefore I am using templateField:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView_Sort">
<Columns>
<asp:TemplateField HeaderText="Control">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" onClick="deleteEntry()" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in my deleteEntry() function how can I know anything about the row in which "Delete" link was clicked? How to ge for e.g. rowindex?
You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.
To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.
<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />
where myObjectID is the name of the ID column of your object you bind the grid to.
Then
void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
if ( e.CommandName == "LinkButtonClicked" )
{
string id = e.CommandArgument; // this is the ID of the clicked item
}
}
Related
I Have a LinkButton In a TemplateField In a GridView. The LinkButton is bound to database which shows the time save in database.All I want is to fetch each linkbutton time value and compare it to current time and if linkbutton time is less than current time ,make it disable.
Any pointers will be helpful.
Thanks in advance.
<asp:GridView ID="grdview" AutoGenerateColumns="false" runat="server" OnRowCommand="grdview_RowCommand">
<Columns>
<asp:BoundField DataField="AudiName" DataFormatString="Audi {0}" HeaderText="Audi Name" />
<asp:TemplateField HeaderText="StartTime">
<ItemTemplate>
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
CommandName="time"
CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
<asp:HiddenField runat="server" ID="hf1" Value='<%#Eval("StartTime")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use the OnRowDataBound event to hook into the data binding and disable the button.
Form
<asp:GridView ID="MyGridView"
OnRowDataBound="MyGridView_RowDataBound"
runat="server">
....
</asp:GridView>
CodeBehind
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the button
var linkButton = (LinkButton) e.Row.FindControl("MyLinkButton");
// Toggle enabled/disabled based on time
// Using the button text is probably a bad idea, but is used here for demonstration purposes
linkButton.Enabled = (Convert.ToDateTime(linkButton.Text) > DateTime.Now);
}
}
The code above has not been tested, but should give you an idea of how you can approach this.
You can set the Enabled property of LinkButton comparing with the current time:
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
Enabled = '<%# ((DateTime)Eval("StartTime")< DateTime.Now )? false : true %>'
CommandName="time" CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
I have web form with a GridView and a few controls in the GridView. I have a DropDownList in the EdtItemTemplate of the gridview.
I am needing to bind this DropDownList with some method in my CodeBehind File that returns a Array of type LisItems.
The problem I am facing is this. Since the Control is sitting in the EditItemTemplate, using the FindControl("MyControlID") does not seem to work in any of the GridView events, it returns null, in other words it cannot seem to find the control, unless I use the OnRowUpdating event, but I cannot use this event as the Control needs to be Data binded before that.
Is there anyway I can use the <%# Bind("MyMethodName") %> to bind the control?
Try this
Create a class of your data in App_Code, Like this
public static class Fruits
{
public static List<string> GetFruits()
{
return new string[] { "Apple", "Mango", "Banana", "Grapes" }.ToList();
}
}
Add a grid to your page, Which I guess you all ready have
<asp:GridView runat="server" ID="grid" AutoGenerateColumns="false" OnRowEditing="grid_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Selected Fruit">
<ItemTemplate>
<asp:Label runat="server" ID="Fruit" Text='<%# Eval("Fruits") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="fruits" DataSourceID="fruitsDS" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And add an Object Datasource to bind your DropDowns of edit template
<asp:ObjectDataSource ID="fruitsDS" runat="server" SelectMethod="GetFruits" TypeName="Fruits" />
Hope this could help.
Try this
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList dl = (DropDownList)e.Row.FindControl("myList");
dl.DataSource = new string[] { "A", "B" };
dl.DataBind();
}
}
gridview rowdatabound will use to bind the data to dropdown in gridview.
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlcity");
ddl.DataSource = s;
I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >
How can I get a value of the DataKeyName of a GridView Row when I have a button inside a row that have an OnClick event. In my OnClick event of my button I want to get a the DataKeyName of the row where the button resides.
Is this possible?
<asp:GridView ID="myGridView" run="server">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
... bunch of html codes
<asp:Button ID="myButton" UseSubmitBehavior="false" runat="server" Text="Click Me" onclick="btnClick_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my codebehind
protected void btnClick_Click(object sender, EventArgs e)
{
// How can I get the DataKeyName value of the Row that the Button was clicked?
}
When I'm working with a GridView, I usually do not use the OnClick event for buttons. Instead, I use the OnRowCommand event on the GridView, and bind data to the CommandArgument property of the button. You can retrieve the command argument from the GridViewCommandEventArgs parameter of the event handler.
You can use the CommandName parameter to bind an arbitrary string to distinguish between any different kinds of buttons you have. Note that some command names are already used for other events, such as "Edit", "Update", "Cancel", "Select" and "Delete".
Update:
Here is an example, assuming the data key is called "ID":
<asp:GridView ID="myGridView" runat="server" OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
... bunch of html codes
<asp:Button ID="myButton" runat="server" Text="Click Me" CommandName="ClickMe" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var datakey = e.CommandArgument;
// ...
}
You can bind the key to the CommandArgument property of the Button, and consume (sender as Button).CommandArgument property in the code
I have a GridView that is populated from a LinqDataSource. When I update a row, the RowCommand fires and the change is persisted to the database, but the Grid does not refresh. I have it in an UpdatePanel and explicitely call Update() in the RowCommand handler, but there is no postback and the page just sits there in Edit mode. Once I click cancel, it will return to view-only and the grid shows the new value.
My suspicion is that something in the wiring of the GridView regarding the data source is wrong. No exception bubbles up, though. A stripped-down copy of the markup is below. Any ideas?
<asp:UpdatePanel ID="uPanel" runat="server" UpdateMode="Conditional"
EnableViewState="true" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:LinqDataSource ID="YieldDataSource" runat="server"
ContextTypeName="myhDataContext" TableName="vw_drug_yields"
OnSelecting="YieldDataSource_Selecting" EnableUpdate="true" />
<asp:GridView ID="YieldGridView" runat="server" Width="900px"
OnRowDataBound="editGrid_RowDataBound"
DataSourceID="YieldDataSource" EnableViewState="true"
OnRowCommand="YieldGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Net Fill" ItemStyle-HorizontalAlign="Center">
<ItemTemplate><%# DataBinder.Eval(Container.DataItem, "net_fill") %>
</ItemTemplate>
<EditItemTemplate><asp:TextBox ID="tbNetFill" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "net_fill") %>' >
</asp:TextBox></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" ItemStyle-Width="40px">
<ItemTemplate>
<asp:ImageButton CommandName="Edit" ID="btnEdit" SkinID="btnEdit"
runat="server" ToolTip="Edit" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton CommandName="Update" ID="btnSubmit" SkinID="btnSubmit"
runat="server" ToolTip="Save" CausesValidation="true"
CommandArgument="<%# ((GridViewRow) Container).DataItemIndex %>" />
<asp:ImageButton CommandName="Cancel" ID="btnCancel" SkinID="btnCancel"
runat="server" ToolTip="Cancel" CausesValidation="false"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView></ContentTemplate></asp:UpdatePanel>
The handler:
protected void YieldGridView_RowCommand(Object sender,
GridViewCommandEventArgs e) {
if (e.CommandName == "Update") {
try {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gdrow = YieldGridView.Rows[index];
// do some validation and handle update
db.SubmitChanges();
YieldGridView.DataBind();
uPanel.Update();
}
catch (Exception ex) {
ShowError(this, "Error while updating yields", ex, true);
}
}
After removing the UpdatePanel and turning off callbacks for the GridView, I received the following error when clicking the Update button:
Could not find a row that matches the
given keys in the original values
stored in ViewState. Ensure that the
'keys' dictionary contains unique key
values that correspond to a row
returned from the previous Select
operation.
The problem is that there is no single unique key for this data, as it is dynamically assembled from different sources. It should not be needed, but it seems that a GridView with LinqDataSource can't function without it.
In addition, I am populating the grid from a View, which does not have a primary key.
The solution involved 3 changes:
disabling updates for the LinqDataSource
changing the command name from Update to MyUpdate (so that Linq does not try to auto-wire it)
setting the YieldGridView.EditIndex = -1 prior to calling Update on the UpdatePanel
Thanks for your help.
Before you call Update(), call GridView.DataBind() to rebind against the LINQDataSource control.
try this:
YieldGridView.DataBind();
//though this seems useless after call to DataBind, but lets just try :)
YieldGridView.EditIndex = -1;
uPanel.Update();