How to edit an entire column for all rows asp:GridView - c#

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;
}
}
}

Related

Update row for specific column on Webform App

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;
}
}

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

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;
}

Page not deleting from DB/Gridview ASP.NET

I'm having problems with my ASP.NET Web application:
I have a Gridview that shows the rows of the "Pages" table on a mdb database; next to the id and the titles are two buttons, Edit and Delete. While the edit button works perfectly, the delete one won't work. I've put breakpoints at the beginning of the delPagina (delete page) method and it seems that such method does not run at all. This is the Gridview Code:
<asp:GridView ID="grdPagine" CssClass="table table-condensed" BackImageURL="../media/img/hbg.png" runat="server" AutoGenerateColumns="false" OnRowDeleting="delPagina">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="titolo" HeaderText="Titolo" />
<asp:TemplateField>
<ItemTemplate>
Modifica
<asp:Button ID="delBut" runat="server" CssClass="btn btn-danger" CommandName="Delete" Text="Elimina" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the delPagina method:
public int delPagina(int _id)
{
Data.DB.OleDbDatabase db = new Data.DB.OleDbDatabase();
string query = "DELETE FROM pagine WHERE id="+ _id;
return db.EseguiNonQuery(query);
}
The Event:
protected void delPagina(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(this.grdPagine.Rows[e.RowIndex].Cells[0].Text);
int b = new PaginaService().delPagina(id);
List<Pagina> pag = new PaginaService().mlistapagine();
this.grdPagine.DataSource = pag;
this.grdPagine.DataBind();
}
Sorry if my terminology is a bit off but this is kind of a new word for me.
Thanks in advance
Edit: When i click on the button there is a page refresh but no gridview is shown, so i have to refresh again manually.
You can use RowCommand and CommandArgument, Please look to following code sample
<asp:GridView ID="grdPagine" CssClass="table table-condensed" BackImageURL="../media/img/hbg.png" runat="server" AutoGenerateColumns="false" OnRowCommand=grdPagine_RowCommand" OnRowDeleting="delPagina">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="titolo" HeaderText="Titolo" />
<asp:TemplateField>
<ItemTemplate>
Modifica
<asp:Button ID="delBut" runat="server" CssClass="btn btn-danger" CommandName="Delete" Text="Elimina" CommandArgument='<%# Bind("id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in code behind declare
protected void grdPagine_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
int b = new PaginaService().delPagina(id);
List<Pagina> pag = new PaginaService().mlistapagine();
this.grdPagine.DataSource = pag;
this.grdPagine.DataBind();
}
}
Hopefully the above code solves your problem
According to your code there is no click event in delBut button
you can use RowCommand event in gridview since your buttons CommandName="Delete"

Checkboxfield value controls button visibility

I have a gridview which displays the contents of a database table in rows. There is a CheckboxField there and a Select button. I want to set button visibility to false when checkboxfield is checked.
this is my aspx page:
<asp:DetailsView ID="DetailsViewERgo" runat="server" Height="50px"
Width="100%" AutoGenerateRows="False" CellPadding="4"
DataSourceID="LinqDataSourceErgo" ForeColor="#333333" GridLines="None"
HeaderText="Σύντομη Περιγραφή Επιλεγμένου Έργου">
<Columns>
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
<asp:TemplateField HeaderText="Insert Answer" ShowHeader="False">
<ItemTemplate>
<center>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Select" Text="Επιλογή" Visible="true" >
</asp:Button>
</center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have tried this but only works with checkboxes
protected void GridViewAitima_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.FindControl("Diekperewsi");
Button b = (Button)e.Row.FindControl("Button1");
if (!cb.Checked)
{
b.Visible = false;
}
else
{
b.Visible = true;
}
}
}
Your code will run on the server side but it looks as if the the AutoPostBack property for your checkbox is not set to true -
AutoPostBack="True"
so when the checkbox is checked the code will not run immediately, it will only run after another event has caused your page to postback.
CheckBoxField has no id thus you can't find it by id, moreover it has no value propertie.
I suggest you use template field just like you used for the button, but instead put a checkbox in it.
so instead of :
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
put :
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Diekperewsi" Enabled="false" Checked='<%#Eval("Diekperewsi")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
and you are good

gridview commandargument on buttonfield pagination used

I am using c#.net
I have a gridview which needs to contain a 'Use' button (appointmentId set as the commandargument).
Source Code
<asp:GridView ID="resultsReturned" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
EnableSortingAndPagingCallbacks="True"
OnPageIndexChanged="resultsReturned_PageIndexChanged"
onrowcommand="resultsReturned_RowCommand">
<Columns>
<asp:BoundField DataField="UserAppointmentId" HeaderText="App ID" />
<asp:BoundField DataField="UserBookingName" HeaderText="Booking Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server"
ID="UseButton"
Text="Use"
CommandName="Use"
CommandArgument="UserAppointmentId" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind
protected void resultsReturned_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Use")
{
correctAppointmentID.Value = (e.CommandArgument.ToString());
}
}
This is used for the pagination:
private void BindAppointments()
{
var results = appointmentRepos.GetBookingIdBySearchCriteria(catgoryid, resultsReturned.PageIndex * resultsReturned.PageSize, -1);
resultsReturned.DataSource = results;
resultsReturned.DataBind();
}
I am binding the appointments to the gridview within the PageLoad/search_Click
This is the error I am receiving:
Callbacks are not supported on TemplateField because some controls cannot update properly in a callback. Turn callbacks off on 'resultsReturned'.
Try the following:
<asp:Button runat="server"
ID="UseButton" Text="Use" CommandName="Use"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.UserAppointmentId") %>' />
and Set EnableSortingAndPagingCallbacks="False"

Categories

Resources