Bind and access checkbox value within a gridview - c#

In my grid view I've a checkbox column, and am binding the gridview with a dictionary. I need to get the corresponding Id from the checked boxes.
In my dictionary I've the key values like
Id Name
-- ----
1 Arts
2 Science
3 Engineering
Here, I tried to bind the value for this checkbox as
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelItem" value="<%# Eval("Key.Id") %>"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<%# Eval("Key.Name") %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
and from the codebehind, I tried like
foreach (GridViewRow row in gridDepartments.Rows)
{
CheckBox chkSelItem = (CheckBox)row.FindControl("chkSelItem");
if (chkSelItem.Checked)
{
int departmentId = int.Parse(chkSelItem.Text);
////
////
}
}
its throwing error, or not showing any value for the checkbox.
I also trid with FindControl, but no use of it, coz in the key & Value pair am using a class(which inherits another class) and a bool. thats what am trying like this, can anyone help me here, thanks in advance.....

You can try this one...
Bind id to lable instead of to checkbox as below.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelItem" runat="server" />
<asp:Label ID="lblSelectedItem" value=<%# Eval("Key.Id")) %> visible="False"/>
</ItemTemplate> </asp:TemplateField>
In codebehind try this
foreach (GridViewRow row in gridDepartments.Rows)
{
CheckBox chkSelItem = (CheckBox)row.FindControl("chkSelItem");
Label lblSelectedItem= (Label)row.FindControl("lblSelectedItem");
if (chkSelItem.Checked)
{
int departmentId = int.Parse(lblSelectedItem.Text);
}
}
Hope this is what u want...

Use
CheckBox chkSelItem = (CheckBox)row.cell[0].FindControl("chkSelItem");// Replace row.cell[0] accrding to you celll index
instead of
CheckBox chkSelItem = (CheckBox)row.FindControl("chkSelItem");

In Aspx page:
<asp:CheckBox ID="chkSelItem" Text="<%# Eval("Key.Id") %>" runat="server" />
In code-behind add a check to ensure the item is not null:
CheckBox chkSelItem = (CheckBox)row.FindControl("chkSelItem");
if (chkSelItem != null && chkSelItem.Checked && !string.IsNullOrEmpty(chkSelItem.Text))
{
int departmentId = int.Parse(chkSelItem.Text);
}

I think you have to use Text instead of value as you are assigning to value and getting text property. Text will be empty string and parsing it with int throws exception.
int.Parse(chkSelItem.Text);
<asp:CheckBox ID="chkSelItem" value="<%# Eval("Key.Id") %>" runat="server" />
Would be
<asp:CheckBox ID="chkSelItem" Text="<%# Eval("Key.Id") %>" runat="server" />
Or
If you have to use Value of check box, then access value not Text
<asp:CheckBox ID="chkSelItem" value="<%# Eval("Key.Id") %>" runat="server" />
int departmentId = int.Parse(chkSelItem.Attributes["value"].ToString());

Related

How to disable checkbox inside gridview?

Hi I am developing one application. I have one multiselect dropdownlist box. Whenever i select one value in dropdownlistbox corresponding value in gridview will be having checkbox in below gridview. I want to disable that checkbox. I am basically mvc developer and finding hard times to fix this. I am trying my level best to fix this. For example, whever i select some value in dropdown I am getting ID using jquery as below.
<script>
$(function() {
$('.limitedNumbSelect2').change(function (e) {
var selected = $(e.target).val();
});
});
This is my gridview.
<asp:GridView ID="gdvRegretletter" CssClass="tableform" runat="server" AutoGenerateColumns="False" DataKeyNames="Vendor_ID"
EmptyDataText="No records found !" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvRegretletter_PageIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="true" HeaderText="Select All">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" Text="Check All" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" />
<asp:HiddenField ID="id" runat="server" Value='<%#Eval("Vendor_ID")%>' />
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle VerticalAlign="Top" Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Whenecer i select some value from multiselect dropdownlist box I get id in a variable selected. As soon as I get ID in a variable selected i want to disable that checkbox in gridview. May i have some suggestions on this! Thank you all
Furthur i tried as below.
This is jquery code to hide checkbox
$('.limitedNumbSelect2').change(function (e) {
selected = $(e.target).val();
`$(".disablechk[Text='selected']").prop("disabled", true);`
This is my checkbox code inside gridview.
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" Text='<%#Eval("Vendor_ID")%>' class="disablechk"/>
I am trying to do whenever i get some value from dropdown slected i want to disable that particular checkbox.
If you are getting comma separated string then split it and make an array
var temp = new Array();
temp = selected.split(",");
then loop through it
$.each(temp, function( index, value ) {
$(".disablechk[Text='" + value + "']").prop("disabled", true);
});
You can loop the GridView HiddenField values and disable the checkbox accordingly.
<script type="text/javascript">
$(function() {
$('.limitedNumbSelect2').change(function (e) {
checkGridView($(e.target).val());
});
});
function checkGridView(selected) {
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).val() == selected) {
var checkbox = $(this).prev();
checkbox.prop("disabled", true);
}
});
}
</script>

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.

Set value of girdview textbox as command argument of button

Here is my grid view
<asp:GridView ID="grvClaimBanks" runat="server" AutoGenerateColumns="false" AllowPaging="false" OnRowCommand="grvClaimBanks_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Sr.No">
<ItemTemplate>
<%#Container.DataItemIndex +1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:TextBox ID="txtMoratoriumPeroid" runat="server">
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkEditProduction" runat="server" CommandArgument='<%# Eval("TextileSLACId") %>' CommandName="EnterClaim" Text="Enter Claim" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now i want to set value of "txtMoratoriumPeroid" as "CommandArgument" of "lnkEditProduction", so i can access that value in Row Command Event of grid view.
Is this possible?
If yes please help...
The way you are bind the TextBox wont give you value change in client side and your TextBox seem empty on server side. You can get current row of command button in RowCommand event and find TextBox to take its value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
TextBox txtMoratoriumPeroid= row.FindControl("txtMoratoriumPeroid") as TextBox;
if(txtMoratoriumPeroid != null)
{
//Your code here.
string txtMoratoriumPeroidText = txtMoratoriumPeroid.Text;
}
No it is not possible to give dynamic CommandArgument on the fly.
But you can achieve this by
LinkButton lbtnSender = (LinkButton)sender;
TextBox txtMoratoriumPeroid = (TextBox)lbtnSender.Parent.Parent.FindControl("txtMoratoriumPeroid");
string MoratoriumPeroid = txtMoratoriumPeroid.Text;

Get the id of selected checkboxes in gridview (Asp.net) 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

Categories