Get the id of selected checkboxes in gridview (Asp.net) c# - c#

I have two columns one for id & other for checkboxes.
i have taken checkboxes inside the gridview.
i wanted to see the checked values inside the gridview , If checkboxes are checked then i want those values i.e id
Asp.net

foreach(Gridviewrow gvr in Gridview1.Rows)
{
if(((CheckBox)gvr.findcontrol("CheckBox1")).Checked == true)
{
int uPrimaryid= gvr.cells["uPrimaryID"];
}
}

What you will have to do is use a template field:
<asp:TemplateField HeaderText="Field">
<ItemTemplate>
<div style="display: block">
<asp:Checkbox Checked='<%# DataBinder.Eval(Container.DataItem,"Field") %>'
runat="server" ID="chkField"></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
Then you can do:
foreach (DataGridRow dr in DataGrid1.Rows)
{
((CheckBox)gvr.FindControl("chkField")).Checked
}
to see if it's checked

in your aspx you have the following
<asp:GridView ID="gridViewID" runat="server" DataKeyNames="DataKey1,DataKey2,DataKey3" >
<Columns>
<asp:TemplateField HeaderText="selected">
<ItemTemplate>
<asp:CheckBox ID="checkBoxID" runat="server"
Checked='<%# Bind("Selected") %>'
OnCheckedChanged="checkBoxID_CheckedChanged"
AccessKey='<%# Container.DataItemIndex %>'
AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your event handler you do something similar to this:
protected void checkBoxID_CheckedChanged(object sender, EventArgs e)
{
var checkbox = (CheckBox)sender;
var rowIndex = Convert.ToInt32(checkbox.AccessKey);
var gridView = GetErhebungModulGridView();
var dataKey = gridView.DataKeys[rowIndex];
if (dataKey != null)
{
var dataKey1 = dataKey["DataKey1"];
var dataKey2 = dataKey["DataKey2"];
var dataKey3 = dataKey["DataKey3"];
//Do something with the variables keys above
}
}

<asp:gridview id="gv" runat="server">
<columns>
<asP:TemplateField>
<Asp:checkbox id="chk" runat="server" />
<Asp:literal id="ltlID" runat="server" visible="false" text='<%#eval("ID")%>' />
</asp:TemplateField>
</columns>
</asp:gridview>
For each row as gridviewrow in gv.rows
if ctype(row.findcontrol("chk"),checkbox).checked then
Dim _ID as integer = ctype(row.findcontrol("ltlID"),literal).text
end if
next

Related

assign a value to checkbox in a grid in code behind

I have following grid in asp.net
<asp:GridView ID="grdDWlocations" CssClass="table table-hover table-striped" runat="server" GridLines="None" ShowHeaderWhenEmpty="True"
EmptyDataText="No data found..." AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="" Visible="true">
<HeaderTemplate>
<asp:CheckBox ID="allDWlocchk" runat="server" Checked="true" Width="10px" onclick="CheckAllgrdReqDW(this)"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk_DWlocReq" runat="server" Checked="true" Width="5px" OnCheckedChanged="chk_Req_CheckedChangedDW_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lbl_DWCode" runat="server" Text='<%# Bind("Ml_loc_cd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lbl_DWDescription" runat="server" Text='<%# Bind("Ml_loc_desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to assign value for "chk_DWlocReq" in code behind
like this
foreach (GridViewRow dgvr in grdDWlocations.Rows)
{
(CheckBox)dgvr.FindControl("chk_DWlocReq")=true;
}
but above one not valid, how can this do properly ?
I believe your code must be changed to:
foreach (GridViewRow dgvr in grdDWlocations.Rows)
{
((CheckBox)dgvr.FindControl("chk_DWlocReq")).Checked=true;
}
Use this:
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
CheckBox myCheckBoxID = row.FindControl("myCheckBoxID") as CheckBox;
}
myCheckBoxID.Checked = true;
}
OR
If you are handling RowDataBound event, it's like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox myCheckBoxID = e.Row.FindControl("myCheckBoxID") as CheckBox;
}
myCheckBoxID.Checked = true;
}
Try the following:
CheckBox checkbox1 = dgvr.FindControl("chk_DWlocReq") as CheckBox;
checkbox1.Checked = true;
I used this code:
ds1.SelectCommand = String.Format("exec myStoredproc");
dv1 = (DataView)ds1.Select(DataSourceSelectArguments.Empty);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (dv1.Table.Rows[i]["ReceiveNotification"].ToString() == "1")
{
((CheckBox)GridView1.Rows[i].FindControl("GV_chkNotification")).Checked = true;
}
else
{
((CheckBox)GridView1.Rows[i].FindControl("GV_chkNotification")).Checked = false;
}
}

How to get the Id from Gridview of Chechbox.checked?

I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex.
when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="check" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and Button Like
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Send Request" />
the code behind button is
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var check = row.FindControl("check") as CheckBox;
if (check.Checked)
{
int Id = Convert.ToInt32(row.Cells[1].Text);
//some logic follws here
}
}
}
but i am getting an error like
Input string was not in a correct format.
What is the error and how to solve it?
Your looping correct.
But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.
Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.
int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);

How to know in which row a button is clicked in asp.net gridView

This is a simple gridView I m using in aspx web page
<asp:GridView ID="Order" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="none"
ItemType="MyProject.Models.TempList" SelectMethod="GetList" >
<Columns>
<asp:BoundField DataField="ItemID" HeaderText="ID" SortExpression="ItemID" />
<asp:TemplateField HeaderText="ItemName">
<ItemTemplate>
<asp:Label runat="server" ID="ItemName" Width="40" Visible="true" text="<%#: Item.Item.ItemName %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price(each)">
<ItemTemplate>
<%#: String.Format("{0:c}", Convert.ToDouble(Item.Item.UnitPrice))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<div style="float:left">
<asp:Button ID="DeleteBtn" runat="server" Text="Delete" OnClick="DeleteBtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have 2+ items in a list<> which is populating the gridView, how can I tell (in the codeBehind.cs) that which Row the "DeleteBtn" was clicked on?
I was using a for loop to iterate every item in gridView using Rows[i] and used a check box to know which item wants to be deleted using a Update button.
But I want to do it directly on a custom created deletebutton.
Thanks in advance, I know I'm missing something silly.
The best way to do that is using CommandName and CommandArgument in your button declaration like that
<asp:Button ID="AddButton" runat="server" CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Add to Cart" />
you can pass any value in the case we pass the rowIndex, you can get a propertie from your object like that CommandArgument="<%# Eval("id") %>" after that you will handle the onRowCommand method
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
hope it helps :)
Use the button's CommandArgument property; assign Container.DataItemIndex to it. Then use the OnRowCommand event of the gridview and grab the index.
Sample aspx:
<asp:Label runat="server" ID="lblMsg" />
<asp:GridView runat="server" id="gvSample" AutoGenerateColumns="false" OnRowCommand="PerformOperation">
<Columns>
<asp:BoundField DataField="RowValue"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandName="MyCustomCommand" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
gvSample.DataSource = Enumerable.Range(0, 10).Select(i => new { RowValue = i });
gvSample.DataBind();
}
protected void PerformOperation(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyCustomCommand")
{
var rowIndex = int.Parse(e.CommandArgument);
lblMsg.Text = string.Format("Button on row index: {0} was clicked!", rowIndex);
}
}
Let the button field be given a CommandName, say for example a unique string myCommandName in the Edit columns dialog box. Don't worry about the CommandArgument. Then, in the Grid view Row command event, you can check which button (i.e. column) is clicked by tracing the command name like if e.commandname = "mycommandname", at the same time the CommandArgument will also be available as String and all we have to do is to converttoint32, something like intSelectedRow = convert.ToInt32(e.CommandArgument) which will give us the selected row's index.

Read gridview cell values and text

I am using the below code to read gridview controls value or text. But it return null value. I can't find out. But the gridview having some record with the value. Please help me to solve this.
GridViewRow row = null;
for (int i = 0; i < grd.Rows.Count; i++)
{
row = grd.Rows[i];
HiddenField file_id = (HiddenField)row.FindControl("FLD_ID");
Label pack_name = (Label)row.FindControl("FLD_NAME");
string text = file_id.Value;
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (isChecked)
{
//Here its comming
}
}
My partial gridview code here
<asp:GridView ID="grd" runat="server" BackColor="#CCCCCC" BorderColor="#93afba"
BorderStyle="Solid" BorderWidth="1px" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" PageSize="50" Width="100%" CellSpacing="2" ForeColor="#93afba"
Font-Size="14px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<%--<asp:CheckBox ID="chkall" runat="server" OnChange="checkAll();" />--%>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="FLD_ID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="lbl_id" runat="server" Value='<%#Bind("FLD_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbl_packname" runat="server" Text='<%#Bind("FLD_NAME") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
i think you want to find Checkbox2 and you are finding chkSelect
please replace this
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
with
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)grd_proforma_bill.HeaderRow.FindControl("Checkbox2")).Checked;
your code is fine.
if you are binding gridview on page load be sure your code is as below block
if (!IsPostBack)
{
//code to bind gridview
}
Change the code to and check:
for (int i = 0; i < grd_proforma_bill.Rows.Count; i++)
{
HiddenField file_id = (HiddenField)grd_proforma_bill.Rows[i].FindControl("lbl_id");
Label pack_name = (Label)grd_proforma_bill.Rows[i].FindControl("lbl_packname");
string text = file_id.Value;
CheckBox cb = (CheckBox)grd_proforma_bill.Rows[i].FindControl("Checkbox2");
bool isChecked = cb.Checked;
if (isChecked)
{
//Here its comming
}
}

CheckBox is used instead of Edit in GridView

I have trying to Edit and Update my GridView in bulk.
I have generated a CheckBox in the first column of my GridView. It works something like this:
If I check a particular row in the GridView, the row gets editable.
Like this I can check as many rows I want to edit the GridView.
I have given a universal button called UPDATE, once after editing all the rows, and click on this button, the GridView is updated looping in each row checking for CheckBox.Check.
The issue I am facing here is that, when I click on any CheckBox in the GridView row, I am not getting TextBox.
I am trying to convert Label to TextBox on checking a CheckBox in the GridView.
So when I check a row, the text corresponding to Label template for that cell goes invisible according to my program, but fails to get the TextBox with the value of that cell.
The code I have tried is this:
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (GridView3.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 3; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)//this condition is not satisfying when I debug the program. what is wrong in this line?
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked)
{
chkAll.Checked = false;
}
}
}
}
UpdateGrid.Visible = isUpdateVisible;
}
The aspx code is:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="Location_Profile_Name">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location_Profile_Name" SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
I have commented the issue I am facing in the program above. Kindly help.
I see that you are mixing to approaches, the Template approach (ItemTemplate, EditTemplate), and some Code-Behind approach (doing things hard-coded in code behind).
For your cenario, i sugest do it in code-behind, to get full control of the situation.
i addapted your code to explain my sugestion. Here is:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location_Profile_Name" SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
<%--Here are the controls that edit this row, we will handle this on code-behind--%>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>' Visible="false"></asp:TextBox>
<asp:Button ID="btnSave" Text="save" runat="server" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The "EditTemplate" was deleted, YOU will handle your own edit template.
protected void OnCheckedChanged(object sender, EventArgs e)
{
//... Your code ...
// Here we find the controls tha we will handle
CheckBox chkAll = (GridView3.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckBox1 = (CheckBox)row.FindControl("CheckBox1");
Label Label2 = (Label)row.FindControl("Label2");
TextBox TextBox1 = (TextBox)row.FindControl("TextBox1");
Button btnSave = (Button)row.FindControl("btnSave");
//GridView3.SetEditRow(row.RowIndex);
if (CheckBox1 != null)
{
if (CheckBox1.Checked)
{
if (TextBox1 != null && Label2 != null)
{
// Shows your "Edit Template"
btnSave.Visible = true;
Label2.Visible = false;
TextBox1.Visible = true;
TextBox1.Text = Label2.Text;
}
}
}
}
}
}
for now, you have the control of situation :)
see this post Edit Update Delete Multiple Records
basically you need to add in your gridview
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
and code behind:
protected void chkSelect_CheckedChanged
(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
TextBox txtname = (TextBox)grdRow.FindControl("txtName");
if (chkTest.Checked)
{
txtname.ReadOnly = false;
}
else
{
txtname.ReadOnly = true;
}
}
if you familiar with Jquery you can easily enable the fields also in client side
Since AutoGenerateEditButton = false, therefore there should be no for Home_Profile. The TextBox template for Home_Profile should be written within and the visibility should be set to false.
The aspx code is:
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
i don't have the code for the way i previously did it, here is a little example using similar logic that what you did, i hope it helps
here is an working example doing it the way you did it
Code Behind
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "Test " + i;
dt.Rows.Add(dr);
}
rptITem.DataSource = dt;
rptITem.DataBind();
}
}
protected void UpdateCB(object sender, EventArgs e)
{
foreach (RepeaterItem Item in rptITem.Items)
{
CheckBox cb = (CheckBox)Item.FindControl("cbTest");
TextBox tb = (TextBox)Item.FindControl("tbTest");
Label lb = (Label)Item.FindControl("lbTest");
tb.Visible = cb.Checked;
lb.Visible = !cb.Checked;
}
}
protected void UpdateAll(object sender, EventArgs e)
{
foreach (RepeaterItem Item in rptITem.Items)
{
CheckBox cb = (CheckBox)Item.FindControl("cbTest");
TextBox tb = (TextBox)Item.FindControl("tbTest");
Label lb = (Label)Item.FindControl("lbTest");
cb.Checked = true;
tb.Visible = true;
lb.Visible = false;
}
} }
Aspx Code
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Repeater ID="rptITem" runat="server">
<HeaderTemplate>
<div style="border:1px solid black">
<div style="width:50px; float:left"><asp:CheckBox ID="cbAll" runat="server" AutoPostBack="true" OnCheckedChanged="UpdateAll" /></div>
<div style="width:200px; float:left;">Name</div>
<div style="clear:both"></div>
</div>
</HeaderTemplate>
<ItemTemplate>
<div style="width:50px; float:left"><asp:CheckBox ID="cbTest" runat="server" AutoPostBack="true" OnCheckedChanged="UpdateCB" /></div>
<div style="width:200px; float:left;"><asp:Label ID="lbTest" runat="server" Text='<%# Eval("Name") %>' ></asp:Label></div>
<div style="width:200px; float:left;"><asp:TextBox ID="tbTest" runat="server" Text='<%# Eval("Name") %>' Visible="false"></asp:TextBox></div>
</ItemTemplate>
<SeparatorTemplate>
<div style="clear:both"></div>
</SeparatorTemplate>
</asp:Repeater>
</asp:Content>

Categories