EditTemplate property of asp:GridView control - asp.net

I have a asp:GridView and in there i have two columns , in one column i want to show label
but when i click an sdit button i want to show a drop down list in that particular column,
i have created the grid view like following:
<bw:GridView ID="grdProducts" AllowPaging="True" PageSize="5" AllowSorting="True"
CssClass="DGTable" runat="server" AutoGenerateColumns="False" DataKeyNames="LinkedProductCode"
RowSelectingEnabled="True" RowStyle-CssClass="DGItem" SelectedRowStyle-CssClass="DGSelectedItem"
FooterStyle-CssClass="DGFooterTR" EditRowStyle-CssClass="DGEditItemValidator" >
<Columns>
<asp:BoundField DataField="LinkedProductCode" HeaderText="Product Code" ReadOnly="true" meta:resourcekey="BoundFieldResource4" />
<asp:TemplateField HeaderText="Product Type" ItemStyle-VerticalAlign="Top">
<ItemTemplate>
<asp:Label ID="lbl1" runat="server" Text='<%# Bind("LinkedProductType")%>' />
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList ID="linkedproductList" runat="server" DataSourceID="list">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle CssClass="DGSelectedItem" />
<PagerStyle CssClass="DGPagerTR" />
<HeaderStyle CssClass="DGHeaderTR" />
</bw:GridView>
what should i do to do it? What should i write in edit button's click event?
Please help..

It depends on how you are setting up the Edit button. If you have
<asp:Button ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" />
within an <ItemTemplate> in the GridView, then the Gridview will automatically go into Edit mode when the Edit button is clicked. The CommandName Edit is a special CommandName to put a GridView into edit mode.
If you wanted to implement some specific behaviour in edit mode, then this can be achieved by setting up an OnRowEditing event handler and implement your logic here. This would look something like this
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
// Set editing on the row that raised the event
GridView1.EditIndex = e.NewEditIndex;
/* Insert specific editing logic here */
GridView1.DataBind();
}

You only need to create a ButtonField with Commandname set to "Edit" (alternatively, set the AutoGenerateEditButton property of the GridView to True).
The GridView supports preconfigured commands for fields that specify a specific set of CommandNames (such as "Edit", "Delete", "Cancel").
When this button is clicked, your GridView will go into "Edit" mode and the EditItemTemplate will automatically be displayed.

Related

Using asp:Button with OnRowDeleting event

I'm trying to connect an asp:Button with my OnRowDeleting event in a gridview, but I don't don't know how to do that :X. I'm currently using CommandField but for my own purposes I need it with a Button instead. Can anyone help me please?
EDIT:
Let me re-explain, I have a row with Delete and Edit buttons in the same CommandField. What I'm trying to do is to hide the 'Delete' button in some specific cases for specific rows only and not necessarily for every row. That's why I'm struggling with a CommandField because there's no ID coming with it so I can't refer to it in my codebehind. But - asp:Button has an ID but I can't manage to link it with the UserAccounts_RowDeleting function. And that's my question - how to link it? :)
EDIT2:
These are part of my codes:
<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#3AC0F2"
HeaderStyle-ForeColor="White" AutoGenerateDeleteButton="false"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AutoGenerateEditButton="false"
onrowcancelingedit="UserAccounts_RowCancelingEdit" RowStyle-ForeColor="#3A3A3A" OnRowEditing="UserAccounts_RowEditing"
PageSize="10" AllowPaging="false" onrowdeleting="UserAccounts_RowDeleting"
OnRowUpdating="UserAccounts_RowUpdating" OnRowDataBound="UserAccounts_RowDataBound" onrowcreated="UserAccounts_RowCreated">
<Columns>
<asp:CommandField ShowDeleteButton="true" ShowEditButton='true' ButtonType="Link" />
<asp:BoundField DataField="UserName" HeaderText="Username" ReadOnly="true"/>
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:CheckBoxField DataField="IsApproved" HeaderText="Approved?" ReadOnly="false"/>
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" ReadOnly="true"/>
<asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" ReadOnly="true"/>
<asp:BoundField DataField="Comment" HeaderText="Comment" NullDisplayText="N/A"/>
<asp:TemplateField HeaderText="Select" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
//Codebehind c#
protected void UserAccounts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (Funcs.GetAdminLevel() >= 999)
{
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
if (username.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
ActionStatus.Text = string.Format("ERROR: You can't delete your own account ('<font color=#000000><b>{0}</b></font>')!", username);
else if (Funcs.GetAdminLevel(username) >= 1)
ActionStatus.Text = string.Format("ERROR: You can't delete administrators' accounts ('<font color=#000000><b>{0}</b></font>')!", username);
else
{
Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
Membership.DeleteUser(username);
ActionStatus.Text = string.Format("User '<font color=#000000><b>{0}</b></font>' has been successfully deleted!", username);
BindUserAccounts();
}
}
else
ActionStatus.Text = "You are not authorized to delete user accounts!";
}
I want to change the CommandField to ItemTemplate so I can enable/disable it through the codebehind for specific rows only. Also, I want the ItemTemplate, which would be asp:Button, to use the UserAccounts_RowDeleting event and that's where my problem is, I just don't know how to link the button to the event..
It sounds like you pretty much have the solution already. Use a TemplateField for your button. The key part is to set the CommandName of your button to "Delete". This tells the GridView that it is a delete button and the RowDeleting event should handle it.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>

How to delete a row in a dynamically generating grid view?

Hello Respected sirs,
I am generating a shopping cart like ordering system, in which i add/bind the productname, productprice, and productquantity from DataTable to GridView.
I have Added an ImageButton to the gridview only for deleting the selected row.
I also know that we can not delete a row from a dynamically generated grid view. so i placed a code in the ImageButton Click event that deletes the row from DataTable (Which is STATIC during the whole process) and again binds the Data With GridView.
Please note that i hv already once bind the data with gridview in my "BTN_ADD TO CART_Clicked".
Here is my code snippet,
protected void gvorderlist_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
DataRow row = dt.Rows[index];
dt.Rows.Remove(row);
gvorderlist.DataSource = dt;
gvorderlist.DataBind();
}
}
and ASP code is,
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am getting an Error which says : The GridView 'gvorderlist' fired event RowDeleting which wasn't handled.
Any help will be appreciated...
Thank You
The error explains everything. You need todefine the event method for OnRowDeleting in markup:
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand" OnRowDeleting="gvorderlist_RowDeleting">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And add an empty method in the code:
protected void gvorderlist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// No need to implement code here
}
The attributes for the GridView are case-sensitive, so change onrowcommand to OnRowCommand and see if that fires when you click the delete button. If not, you'll need to define OnRowDeleting explicitly. (Also change the capitalization of onpageindexingchange)
Give Command Name=D instead of Delete. It searches for Row_Deleting event when Command Name =Delete.

ASP.NET How to show AjaxControlToolkit Modal Popup from CheckBox

I need to show an AjaxControlToolkit ModalPopupExtender control, when user checks/unchecks a CheckBox control that is inside a GridView as a TemplateField.
-- Updated on 24/05/2013
See final solution here...
We finally solved the problem. So I decided to post here the complete solution and the final code.
The GridView
<asp:GridView ID="gvDocs" runat="server" CssClass="grid" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="gvDocs_PageIndexChanging"
OnSorting="gvDocs_Sorting"
OnRowDataBound="gvDocs_RowDataBound">
<AlternatingRowStyle CssClass="grid_row_alternate"/>
<HeaderStyle CssClass="grid_header" />
<RowStyle CssClass="grid_row" />
<SelectedRowStyle CssClass="grid_row_selected" />
<Columns>
<asp:BoundField DataField="ID"/>
<asp:BoundField DataField="COLUMN_A" SortExpression="COLUMN_A" HeaderText="COLUMN_A" />
<asp:BoundField DataField="COLUMN_B" SortExpression="COLUMN_B" HeaderText="COLUMN_B" />
<!-- TemplateField with the CheckBox and the ModalPopupExtender controls -->
<asp:TemplateField HeaderText="Check" SortExpression="CHECK_COLUMN">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
<!-- Modal Popup block -->
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" BackgroundCssClass="modalBackground" DropShadow="True" TargetControlID="CheckBox1" PopupControlID="panModalPopup" CancelControlID="CancelButton"/>
<asp:Panel ID="panModalPopup" runat="server" style="display:none; text-align:left; width:400px; background-color:White; border-width:2px; border-color:#40A040; border-style:solid; padding:10px;">
Are you sure?
<br /><br />
<div style="text-align:right;">
<asp:Button ID="ConfirmButton" runat="server" Text="Confirm" OnClick="ConfirmButton_Click" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'/>
<asp:Button ID="CancelButton" runat="server" Text="Cancel"/>
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
The code behind
protected void gvDocs_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
// Setting the CheckBox check reading the state from DB
CheckBox CheckBox1 = (CheckBox)e.Row.FindControl("CheckBox1");
CheckBox1.Checked = DataBinder.Eval(e.Row.DataItem, "CHECK_COLUMN").ToString() == "Y"; // Or any other value that works like true/false
}
}
protected void ConfirmButton_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument; // Get the ID column value
// Update the CHECK_COLUMN value on the DB or do whatever you want with the ID...
BindData(); // Method that do the GridView DataBind after the changes applied to the DB
}
Some things to know
1) The ModalPopupExtender1 control is inside the GridView TemplateField because it needs to have access to the CheckBox1 and its click event. It's probably not the best solution ever, but it works and so it would not affect to much on performance if your GridView is not too complicated and if it is paged.
2) In order to catch the ConfirmButton Click event, you have to remove the OKControlID property from the ModalPopupExtender control settings.
-- END
-- Updated on 22/05/2013
Then I need the ID of the corresponding row to make an UPDATE on the DB.
-- END
This is the GridView
<asp:GridView ID="gvDocs" runat="server" CssClass="grid" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="gvDocs_PageIndexChanging"
OnSorting="gvDocs_Sorting"
OnRowDataBound="gvDocs_RowDataBound">
<AlternatingRowStyle CssClass="grid_row_alternate"/>
<HeaderStyle CssClass="grid_header" />
<RowStyle CssClass="grid_row" />
<SelectedRowStyle CssClass="grid_row_selected" />
<Columns>
<asp:BoundField DataField="ID_DOCUMENTO" Visible="False"/>
<asp:BoundField DataField="NUM_PROT" SortExpression="NUM_PROT" HeaderText="N. Prot." />
<asp:BoundField DataField="DATE_PROT" SortExpression="DATE_PROT" HeaderText="Data Prot." />
... some other BoundFields ...
<asp:TemplateField HeaderText="Da archiviare" SortExpression="DA_ARCHIVIARE">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="chkArchiviare" runat="server" AutoPostBack="True" OnCheckedChanged="chkArchiviare_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
And this is the ModalPopup block
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True" TargetControlID="panModalPopup" PopupControlID="panModalPopup" OkControlID="btnConferma" CancelControlID="btnAnnulla" />
<asp:Panel ID="panModalPopup" runat="server" style="display:none; width:400px; background-color:White; border-width:2px; border-color:Black; border-style:solid; padding:20px;">
Are you sure?
<br /><br />
<div style="text-align:right;">
<asp:Button ID="btnConferma" runat="server" Text="Conferma" OnClick="btnConferma_Click"/>
<asp:Button ID="btnAnnulla" runat="server" Text="Annulla" OnClick="btnAnnulla_Click" />
</div>
</asp:Panel>
Now, I want to show the ModalPopup each time a checkbox is checked/unchecked and that popup have to show a confirmation message with 2 buttons: Confirm and Cancel.
Confirm have to do an update on the DB and then postback.
Cancel have only to hide the popup without postback.
I know that ModalPopupExtender listens to OnClick events. So, do I necessary need a Button, LinkButton, ImageButton, etc. or can I do what I want?
You are right, it listens to onclick events, but client-side ones, so, the target control of the extender can be anything you can click on, even a div or a label.
try to show/hide ModalPopupExtender1 from chkArchiviare_CheckedChanged event like this.
ModalPopupExtender1.show();
and
ModalPopupExtender1.hide();
take one Hidden button and make it as TargetControlID like this.
<asp:HiddenField ID="btnHiddenDtl1" runat="Server" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True" TargetControlID="btnHiddenDtl1" PopupControlID="panModalPopup" OkControlID="btnConferma" CancelControlID="btnAnnulla" />
you need not to call cancel button click event to hide ModalPopupExtender1.
You no need to include ModalPopup Extender inside your GridView. You can bind check box control in template field in GridView and use OnCheckedChanged property in it...So template would be like below
<asp:TemplateField HeaderText="Da archiviare" SortExpression="DA_ARCHIVIARE">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="chkArchiviare" runat="server"
OnCheckedChanged="chkArchiviare_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
After this you have to call show function on chkArchiviare_CheckedChanged event...like this
ModalPopupExtender1.Show();
Here ModalPopupExtender1 is ID of you ModalPopupExtender control.
One more thing you have to remember use one button on .aspx page. And pass this button ID into ModalPopupExtender TargetControlID... Like this
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True"
TargetControlID="btnShowModalPopup" PopupControlID="panModalPopup"
OkControlID="btnConferma" CancelControlID="btnAnnulla" />
<asp:Panel ID="panModalPopup" runat="server" style="display:none; width:400px;
background-color:White; border-width:2px; border-color:Black; border-
style:solid; padding:20px;"> Are you sure?<br /><br />
<div style="text-align:right;">
<asp:Button ID="btnConferma" runat="server" Text="Conferma"
OnClick="btnConferma_Click"/>
<asp:Button ID="btnAnnulla" runat="server" Text="Annulla"
OnClick="btnAnnulla_Click" />
</div>
</asp:Panel>
Here Why Iam using this button?....There is no use of this button because we are using show() in codebehind...but if we are not pass button Id to ModapPopupExtender TargetControlId property. It will give you an error.
So using ModalPopupExtender in this way...you can use it with LinkButton, Label, Button. For more details with example, you can check the below link....
How to Use ModalPopup Extender into GridView
I hope this article will clear your all doubts....Enjoy and share this with others...Thanks!

ASP.NET Grid View Problem

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" .... >

GridView: Get datakey of the row on button click

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

Resources