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.
Related
I have searched here and on google as well.Things are not working so I'm posting this.
I have two controls GridView and FormView.I am using Model binding in my project.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
AutoGenerateColumns="false" SelectMethod="Select_GridView">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile" >
I want to open FormView in Edit mode , where in gridview i am sending id of that record.On button click i want to change formview mode by calling BLL method which takes that Id from button click and retrieved record displayed in form view in edit mode.
Please help me , how can i implement this or any other similar way using model binding only,
Thank you.
As no one seems to answer this.I have found work around and also proper method for doing,I will add the answer as i get time from work.
before
asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile"
after
asp:Button ID="Edit_Profile" OnCommand="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView" SelectMethod="Get"
DefaultMode="Insert" InsertMethod="Insert_Profile"
protected void btnEdit_OnClick(object sender, CommandEventArgs e)
{
gId = Convert.ToInt32(e.CommandArgument.ToString());
fvProfile.ChangeMode(FormViewMode.Edit);
fvProfile.Visible = true;
GridView1.Visible = false;
fvProfile.DataBind();
}
public DAL2.Models.OfficialDocument Get()
{
if(gId == 0)
{
ChangeViewMode();
return null;
}
BLL.ManageOfficialDocument mod = new BLL.ManageOfficialDocument();
var od = mod.GetById(gFILES_ID);
return od;
}
private int gId;
I have grid view
one column is ItemTemplate column which has Checkbox field.
Other 2 columns are Databound columns. One column is ButtonField which is of Button type.
I want this button to initially set to disabled mode
Once the Checkbox is checked it should be enabling that particular row button field. Could anyone help in this?
My sample try
.aspx file
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Button" />
</Columns>
</asp:GridView>
.aspx.cs file
protected void CheckBox2_CheckedChanged1(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gridrow = ((GridViewRow)(chk.Parent));
if (chk.Checked)
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = true;
}
else
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = false;
}
}
Try using the below code:
ASPX code for the GridView1:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind (for CheckBox Check Changed Event handler):
protected void CheckBox2_CheckedChanged1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView3.Rows)
{
((Button)row.FindControl("Button1")).Enabled = ((CheckBox)row.FindControl("non_prod_all_select")).Checked;
}
}
Changes made:
1.Set AutoPostBack for CheckBox to true.
2.Removed Button Field and added a template field with button in the third column of the Grid (so that the asp:Button control could be read easily in code behind)
3.Changed the code behind code to do the necessary.
NOTE: I have checked this code locally and is working as expected. So just replace your old code with this and let me know in case of any issues.
I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="MatrĂcula" runat="server" Text="MatrĂcula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.
I am having trouble when trying to fire a button in a GridView with the parameter CommandName = "x", I try to reach my "If" in the GridView1_RowCommand event but I just cant for some reason, if you could help me I'd be gratefull .
This is my .aspx part
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
EnableModelValidation="True" ForeColor="#333333" GridLines="None"
Height="193px" Width="968px" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SOURCE1" onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button Text = "Seleccionar" runat="server" CommandName="X" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="IDEmpresa" HeaderText="IDEmpresa"
SortExpression="IDEmpresa" />
</Columns>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
And this is my C# code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "X")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label1.Text = "WOW It reached out";
}
}
I followed the instructions of the ASP.net page, and im fairly new to .net (I dont know if the UpdatePanel has something to do with it)
Doing a quick test, the code you have provided works, but I did have to wire up my own datasource.
What you are missing here is that Label1 is outside of your UpdatePanel and will not refresh based on your localized postback within the UpdatePanel.
A word of caution with GridViews and UpdatePanels/Buttons. Make sure you are not manually binding/rebinding during Page_Load, and if you have code to do so, you do so within an if(!IsPostBack) { } statement.
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" .... >