Add a checkboxes column to a gridview - c#

I have a gridview that displays data coming from an SQL data source (stored procedure) and I want to add a checkboxex column to it, here is my code:
TemplateField field = new TemplateField();
field.HeaderText = "Exporter ?";
gv.Columns.Add(field);
CheckBox cb = new CheckBox();
cb.Visible = true;
The problem is that I don't know how to add a checkbox to the TemplateField that I added to my gridview columns.

1) Add below code to GridView columns.
<asp:TemplateField HeaderText="CheckBoxColumn" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="checkBox" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
2) Make checkbox column visible dynamically by adding OnRowDataBound event or just looping through GridView.Rows
int indexOfCBColumn = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[indexOfCBColumn].Visible = true;
}
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
row.Cells[indexOfCBColumn].Visible = true;
}
}
Thanks!!

You can add the code below into the GridView Columns.
<asp:templatefield HeaderText="Check Box">
<itemtemplate>
<asp:checkbox ID="cb" runat="server"></asp:checkbox>
</itemtemplate>
</asp:templatefield>

Related

How to refer to which row was selected when i click textbox in gridview?

I have a gridview, inside the gridview is a textbox on templatefield, how do i get the row index of the clicked textbox when i change its value?
<asp:GridView ID="productView" runat="server" BorderWidth="3px" CellPadding="4" CellSpacing="2" AutoGenerateColumns="False" Width="1000px" OnSelectedIndexChanged="productView_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Sacks">
<ItemTemplate>
<asp:TextBox ID="txtSacks" runat="server" CssClass="form-control" Text ="0" Width="100px" OnTextChanged="txtSacks_TextChanged" AutoPostBack="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs:
protected void txtSacks_TextChanged(object sender, EventArgs e)
{
//Rowindex of the texbox
}
Get it using RowIndex
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
You can get the GridViewRow via the NamingContainer property of the TextBox:
protected void txtSacks_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox) sender;
GridViewRow row = (GridViewRow) txt.NamingContainer;
int rowIndex = row.RowIndex;
}
This is better than using txt.Parent.Parent because it still works even with nested controls (f.e. if you want to add the TextBox to a Table or Panel).

Set the current value of gridview DDL on EditItemTemplate

How do I set the selected value in a gridview dropdownlist to what is in the current record like I currently do for a text box.
I am hoping the user can look at the current values and decide if they need to be changed -- this is what I use for a textbox:
<asp:TemplateField HeaderText="Other Notes" SortExpression="Other Notes" HeaderStyle-Wrap="false">
<edititemtemplate>
<asp:TextBox ID="txtOtherNotes" runat="server" Text='<%# Eval("[Other Notes]") %>' DataTextField="Other Notes" DataValueField="Other Notes"></asp:TextBox>
</edititemtemplate>
<itemtemplate>
<asp:Label runat="server" Text='<%# Bind("[Other Notes]") %>' ID="lblOtherNotes"></asp:Label>
</itemtemplate>
</asp:TemplateField>
You will need to use the OnRowDataBound event for that.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if the row is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//find the dropdownlist in the row using findcontrol
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList");
//fill the dropdownlist from code behind if needed
ddl.DataSource = source;
ddl.DataTextField = "key";
ddl.DataValueField = "valee";
ddl.DataBind();
//cast the dataitem back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//set the correct listitem as selected
ddl.SelectedValue = row["myValue"].ToString();
}
}
}
I ended up using:
SelectedValue='<%# Bind("myID") %>'
to display the current record in the ddl.

Add a drop down list to a GridView cell

I want to make a column in the GridView a drop down list so the user can select an option from this list.
GridView code:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBooking_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false" />
<Columns>
<asp:BoundField DataField="FinishTime" HeaderText="Finish Time"></asp:BoundField>
<asp:BoundField DataField="TimeSpentName" HeaderText="Time Spent By"></asp:BoundField>
</Columns>
</asp:GridView>
Code Behind:
protected void gvBooking_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
int count = 1;
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
count++;
}
}
}
In the code behind I changed the cell for FinishTime to a textbox. And when the user enters a value in here it calls a function that updates the database.
How do I change the cell to become a drop down menu? Can I do it did in the code behind like I created the textbox or would it be better to change the Boundfield in the GridView
I think you have to start using TemplateField instead of BoundField. Then you can put a TextBox and/or DropDownList directly in the GridView. You can then save the changes with the OnRowCommand event.
<asp:GridView ID="gvBookings"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
OnRowCommand="gvBookings_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1"
runat="server"
Text='<%# Eval("FinishTime") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButton1"
runat="server"
CommandName="saveTextBox"
CommandArgument='<%# Container.DataItemIndex %>'>Save</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1"
runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the dropdownlist in the current row with findcontrol and cast back to one
DropDownList dropDownList = e.Row.FindControl("DropDownList1") as DropDownList;
//add some listitems
dropDownList.Items.Insert(0, new ListItem("Text A", "A"));
dropDownList.Items.Insert(1, new ListItem("Text B", "B"));
dropDownList.Items.Insert(2, new ListItem("Text C", "C"));
//select a value in the dropdown
dropDownList.SelectedValue = "B";
}
}
protected void gvBookings_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandname
if (e.CommandName == "saveTextBox")
{
//convert the commandargument to a row number
int rowNumber = Convert.ToInt32(e.CommandArgument);
//find the textbox in the current row with findcontrol and cast back to one
TextBox textBox = gvBookings.Rows[rowNumber].FindControl("TextBox1") as TextBox;
//do stuff with the textbox value
Label1.Text = textBox.Text;
}
}

C# getting selected value from dropdownlist in gridview asp net

How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

how to populate a list from a asp .net grid view?

I have a Grid View, I want to update all the rows that will be selected by checking the checkbook. First I want all the selected rows into a list. I don know how to do it. I know how to populate a grid from a list.
my grid view is
<asp:GridView runat="server" ID="GridForResult"
Visible="true"
ShowHeader="false"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField ItemStyle-Width="120px" ItemStyle-Height="22px">
<ItemTemplate>
<%#Eval( "TestRoll")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="150px" ItemStyle-Height="22px">
<ItemTemplate>
<%#Eval( "Name")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="80px" ItemStyle-Height="22px">
<ItemTemplate>
<%#Eval( "Program")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="80px" ItemStyle-Height="22px">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Text="Selected" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My another problem is How to get only the selected (checkboxes) rows from the gridview?
Its pretty straight forward if you are not paging your grid and you want to maintain checked value on PostBack.
On GridView Markup, set DataKeyNames="{your primary key}"
Code - behind
List<string> primaryKeys = new List<string>();
foreach(GridViewRow row in GridForResult.Rows)
{
CheckBox check = row.FindControl("chkSelected") as CheckBox;
if(check.Checked)
{
primaryKeys.Add(GridForResult.DataKeys[row.RowIndex].Value.ToString());
}
}
The List<string> primaryKeys will now hold all the checked primary keys.
List<string> objList = new List<string>();
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox CheckBox1 = (CheckBox)gvrow.FindControl("CheckBox1");
if (CheckBox1.Checked)
{
objList.Add(row["id"].Text);
}
}
I would make the checkboxes column a TemplateColumn. Then on postback you need to iterate the GridView Rows Collection and do something like this:
foreach(GridViewRow row in gridViewId)
{
CheckBox chk = row.FindControl("CheckBoxId") as CheckBox;//use chk value as needed
}
declare a collection of say string type,
List<string> objList = new List<string>();
foreach(GridViewRow row in gridViewId)
{
CheckBox chk = row.FindControl("CheckBoxId") as CheckBox;
if(chk.IsChecked)
{
objList.Add(row["id"].Text);
}
}
save this list in session,
Session["checkedList"] = objList;
when you want to retireve,use,
objList = List<string>(Session["checkedList"]);

Categories

Resources