I have a table which contains recipe for each item. Actually I wanted to update my specific column in the table. This table contains Item ID,Stock Code,Stock Name,Stock Group Name,Stock Unit Name,Amount Needed indexes. First of all ı could update and it is working, but when I want to update only my Amount column but when I press edit button, the TextBox opens for each columns. I want only amount row for the TextBox open.
This is the code:
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal" OnRowDeleting="grdItems_RowDeleting" OnRowEditing="grdItems_RowEdit" meta:resourcekey="GridView5Resource1" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete" BackColor="DarkRed" style="color: White" />
<%-- <asp:Button ID="btnUpdate" runat="server" CausesValidation="false" CommandName="Update" Text="Update" BackColor="Green" style="color: White" />
--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" BackColor="Green" style="color: White" />
<asp:Button Text="Cancel" runat="server" OnClick="OnCancel" BackColor="DarkRed" style="color: White"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="_IdItemHam" HeaderText="Item ID" SortExpression="_IdItemHam" meta:resourcekey="BoundFieldResource9" />
<asp:BoundField DataField="item_code" HeaderText="Item Code" SortExpression="item_code" meta:resourcekey="BoundFieldResource1" />
<asp:BoundField DataField="item_name" HeaderText="Item Name" SortExpression="item_name" meta:resourcekey="BoundFieldResource2" />
<asp:BoundField DataField="item_group_name" HeaderText="Item Group Name" SortExpression="item_group_name" meta:resourcekey="BoundFieldResource3" />
<asp:BoundField DataField="item_unit_name" HeaderText="Item Unit" SortExpression="item_unit_name" meta:resourcekey="BoundFieldResource4" />
<asp:BoundField DataField="_Amount" HeaderText="Amount Needed" SortExpression="_Amount" ReadOnly="false" meta:resourcekey="BoundFieldResource6" />
<%--<asp:BoundField DataField="PROC" HeaderText="PROC" SortExpression="PROC" meta:resourcekey="BoundFieldResource8" />--%>
</Columns>
<SelectedRowStyle BackColor="#CCCCFF" />
</asp:GridView>
And here is my .cs code:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
string amount = (row.Cells[6].Controls[0] as TextBox).Text;
//DataTable dt = ViewState["dt"] as DataTable;
//dt.Rows[row.RowIndex]["Amount Needed"] = amount;
//ViewState["dt"] = dt;
((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials.ElementAt(grdItems.EditIndex)._Amount = Double.Parse(amount);
grdItems.EditIndex = -1;
grdItems.DataSource = ((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials;
grdItems.DataBind();
CalculateProductCost();
}
Can you please help me about how to make that event. Thanks from now!
I would suggest you use the event OnRowUpdating, implemented in the GridView.
After that you can get the values and keys in the event, do your save statement and bind the grid.
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal"
OnRowUpdating="grdItems_RowUpdating">
.cs code:
protected void grdItems_RowUpdating(object sender, GridViewUpdateEventArgs e){
object id = e.Keys["_IdItemHam"];
int amount = Convert.ToInt32(e.NewValues["_Amount"]);
//Do your update statment
//After that bind the grid
grdItems.DataBind();
}
use GridView_RowCommand to implement edit action
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow row;
GridView grid = sender as GridView;
switch (e.CommandName)
{
case "Edit":
index = Convert.ToInt32(e.CommandArgument);
row = grid.Rows[index];
//use row to find the selected controls you need for edit, update, delete here
break;
}
}
Related
I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}
I have a Gridview which also contains a button field. When this button on a particular row is clicked, I want it to update my database. For example, if a row contains (SN = 1) I want it to update the button to update the database with the row that contains "SN = 1". How do I get the SN of the row when the button on that same row is clicked?
This is my Gridview definition:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>
Here, when the row button is clicked, I want to update my database with the signout time. I can't seem to get it to get the SN of the row and update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
}
}
If the value you seek is the comes from the same datasource, you can add the value as a CommandArgument:
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out"
runat="server"
Text="Sign out"
CommandName="SignOut"
CommandArgument='<%# Eval("SN") %>'/>
</ItemTemplate>
</asp:TemplateField>
On your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
string sn = e.CommandArgument.ToString();
if (sn == "1")
{
/*DO STUFF....*/
}
}
}
i have a system that adds items into the DataGrid, my question is how can i use the delete button? when the user wants the item deleted, user will press the button to delete the row, but i cant seem to make it work. thank you!
<asp:GridView runat="server" ID="gridview" CssClass="table-hover" AutoGenerateColumns="true" HeaderStyle-BackColor="CornflowerBlue" BackColor="White" BorderWidth="5" BorderColor="CornflowerBlue" OnSelectedIndexChanged="gridview_SelectedIndexChanged" CellPadding="8"
CellSpacing="0" Width="100%" OnRowDeleting="gridview_RowDeleting" EmptyDataText="No records to display">
<HeaderStyle BackColor="CornflowerBlue"></HeaderStyle>
<Columns>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" />
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="lnkEdit" runat="server" ImageUrl="~/Images/Icons/Modify.png" OnClick="Edit" />
<%--<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my script
<script runat="server">
void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gridview.Rows[e.RowIndex].Cells[2];
}
</script>
grid view picture
In Gridview add OnRowCommand="gridview_RowCommand"
CommandField can work but I go like this:
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:Button ID="lnkDel" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
In code behind
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del") {
//Get Command Argument
int IdToDelete = Convert.ToInt32( e.CommandArgument.ToString());
//Your Delete Command
//Rebind GridView
}
}
This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}
So I have google'd and searched stackoverflow, and now my brain is overloaded. I am a novice at asp.net, but getting the hang of it.
My current requirement is to have a gridview where upon load, 1 column for all rows is immediately placed into edit mode. I used this question and code to get me going:
Allowing one column to be edited but not another
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
allowpaging="true"
datakeynames="CustomerID"
runat="server">
<columns>
<asp:boundfield datafield="CustomerID" readonly="true" headertext="Customer ID"/>
<asp:boundfield datafield="CompanyName" readonly="true" headertext="Customer Name"/>
<asp:boundfield datafield="Address" headertext="Address"/>
<asp:boundfield datafield="City" headertext="City"/>
<asp:boundfield datafield="PostalCode" headertext="ZIP Code"/>
</columns>
</asp:gridview>
I have searched and found a few good solutions, however, I do not fully understand them and have been unsuccesful at implementing them. They are:
Edit/Update a single GridView field
Put multiple rows of a gridview into edit mode
So my question is, how would you go about placing a column, (e.g, ZIP Code) into edit mode for all rows at the same time?
All help is appreciated!
Thanks!
Stephen
You won't be able to use the built-in edit functionality, but you can achieve this by loading the column in edit mode using a TemplateField:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SomeColumn") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SomeOtherColumn" HeaderText="Foo" />
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Update" CommandArgument='<%# Container.ItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = GridView1.Rows[(int)e.CommandArgument];
if (row != null)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}
EDIT: Putting a button outside of the GridView, you would update like this:
<asp:GridView>
...
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}