Gridview multiple checkbox selection - asp.net

I want to check multiple item checkboxes without clicking on the checkbox, rather than on other clicking columns.
Here is my **.cs code
private void gridView2_RowClick(object sender,DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (gridView2.GetSelectedRows().Count() > 0)
{
foreach (int i in gridView2.GetSelectedRows())
{
gridView2.SelectRow(i);
}
}
}
And, this is my **.designer.cs code
this.gridView2.OptionsSelection.MultiSelect = true;
this.gridView2.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
this.gridView2.OptionsSelection.ShowCheckBoxSelectorInGroupRow = DevExpress.Utils.DefaultBoolean.True;

Ok, assuming a gridview?
We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table table-hover" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Check Test" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnClick="MyCheckBoxClick(this);"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script>
function MyRowCheck(ctrl) {
MyCheckBox = document.getElementById(ctrl);
MyCheckBox.checked = !MyCheckBox.checked
}
function MyCheckBoxClick(ct) {
ct.checked = !ct.checked
}
</script>
code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
}
void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT TOP 12 * from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox MyCheckBox = (CheckBox)e.Row.FindControl("CheckBox1");
e.Row.Attributes["onclick"] = "MyRowCheck('" + MyCheckBox.ClientID + "');";
}
}
So, we just attach a ROW click to the grid.
We get this output:
this works fine and a click on the row will toggle the check box.
but, the PROBLEM is then if you actually click on the check box. The Row click fires toggles the check box, and then the check box click ALSO fires and un-does what you just did!!
So, I added the on-click event to the check box - and we just toggle the setting again, and we are good to go.

Related

Get clicked cell in gridview asp.net

I got gridview that I fill with data from my database. I would like to catch an event of click and to get attributes of the cell row and column.
all I found is row click that I can get the row clicked.
also, if there is other component to deploy the data and can get me the cell click event is good enough for me.
HTML:
<div class="grid">
<asp:GridView ID="HistoricGrid" runat="server"></asp:GridView>
</div>
C#
DBconnection db = new DBconnection();
string strtable = "select * from StudentVisit";
DataTable dt = db.ReadDataTable(strtable);
HistoricGrid.DataSource = dt; HistoricGrid.DataBind();
thanks for the help,
Moshe
You should try this.
<asp:GridView ID="GridView1" AutoGenerateColumns="False" ShowHeader="True" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Value" DataField="ItemValue" ReadOnly="true" />
<asp:BoundField HeaderText="Text" DataField="ItemText" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton1");
if (linkButton != null)
{
linkButton.Attributes.Add("onclick", "window.open('someURL'); return false;");
}
}
}
You can use below code
private void gv_Cell_Click(object sender, GridViewCellEventArgs e)
{
int cellindex=e.CellIndex;
int rowindex =e.rowindex;
var value = gv.Rows[rowindex].Cells[cellindex].value;
}

Button Click event is not fired in gridview button is added at RowDataBound event

my .aspx design source code is
<asp:GridView ID="grdPaymentStatus" runat="server"
AutoGenerateColumns="false"
CssClass="table table-responsive table-striped table-bordered table-advance table-hover"
HeaderStyle-CssClass="ProjectStatusHeader"
OnRowDataBound="grdPaymentStatus_RowDataBound" >
<Columns>
<asp:BoundField DataField="instCount" HeaderText="Installments" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPayment" HeaderText="Amount" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instWord" HeaderText="Words" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPaymentMode" HeaderText="Payment Mode" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instPaymentdat" HeaderText="Payment Done On" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
<asp:BoundField DataField="instIspaid" HeaderText="Payment Status" HeaderStyle-BackColor="#dddddd" HeaderStyle-Font-Bold="false" />
</Columns>
</asp:GridView>
.aspx.cs code is
protected void grdPaymentStatus_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text != "Paid")
{
Button sendRequestButton = new Button();
sendRequestButton.ID = "PaymentRequest" + Row.Cells[0].Text;
sendRequestButton.Text = "Send Request";
sendRequestButton.CssClass = "btn blue";
sendRequestButton.UseSubmitBehavior = false;
sendRequestButton.CausesValidation = false;
sendRequestButton.Click += new EventHandler(sendRequestButton_OnClick);
e.Row.Cells[2].Controls.Add(sendRequestButton);
}
}
}
protected void sendRequestButton_OnClick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(AckNo))
BindDetailsPayment(AckNo);
}
Data is binding at page load in (! isPostback) method and whenever i am trying to click on button added in gridview the button click event (sendRequestButton_OnClick) is not firing
please help me out
thanks in advance.....
Even though you bound it on row bound, you need to handle the event in RowCommand.
See the following link.

Remove TemplateField during page load or before databind

I want to remove templatefield from gridview during pageload or before databind to GridView. I have 2 data sources for retrieving data. The data retrieved from one of the data sources do not have the columns ExpireDate and ExpireDays.
So I want to delete the templatefields corresponding to ExpireDate and ExpireDays if the GridView is populated from the data source that do not have those 2 fields.
Setting the visibility to false still will have error of DataRowView doesn't contain property name ExpireDate and ExpireDays.
Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="No."/>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="CourseName" HeaderText="Course Enroll" />
<asp:BoundField DataField="SubMember" HeaderText="ChildMember" />
<asp:TemplateField HeaderText="Expiry Days">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDsL" Text=' <%# Eval("ExpiryDays") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry On">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDeL" Text=' <%# Eval("ExpiryDate") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/editB.gif" ID="btnEdit" runat="server" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Eval("ID") %>' />
<asp:ImageButton ImageUrl="~/Images/delB.gif" ID="btnDelete" runat="server" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(Class.ToLower() != "classAA")
{
// using naveen answer can remove the column.
var expiryDateF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry Days").SingleOrDefault());
var expiryDaysF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry On").SingleOrDefault());
if (expiryDateF != null)
{
GridView1.Columns.Remove(expiryDateF);
}
if (expiryDaysF != null)
{
GridView1.Columns.Remove(expiryDaysF);
}
}
if(!this.IsPostBack)
{
BindData();
}
}
protected void SaveMember(object sender, EventArgs e)
{
//getting member information and perform checking.
bool success = dbbb.AddMem(memberdetails);
if(success == true)
{
BindData();
}
else
{
//prompt fail message.
}
}
protected void BindData()
{
DataTable dt = dbbb.RetrieveList();
if(dt != null)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnDel = (ImageButton)e.Row.FindControl("btnDelete");
btnDel.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this member?')");
}
}
How could I delete the column?
Two methods to achieve this
Method 1 - Remove by Index
if(!table.Columns.Contains("CustomerID1"))
{
//seven is the column index here. ie, 8th column
CustomersGrid.Columns.RemoveAt(7);
}
Method 2 - Remove using Columns Header Text
var expiryDateField= ((DataControlField)CustomersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Expiry Date")
.SingleOrDefault());
if(expiryDateField != null)
{
CustomersGrid.Columns.Remove(expiryDateField);
}
Please not that
CustomersGrid is the name of the asp:GridView here.
table is the DataTable that acts as the DataSource of the GridView
The code should be called before DataBind of the GridView
Attach to the rowDataBound event of the grid, there you can set it dynamically.
You have to know the datasource name of the field you want to hide,
for example the headertext for the cell is "SomeHeader", but the databoundfield name for that cell is
"SomeOtherName"
then you have to check it like this (debug through GetColumnIndexByName) and
check the value of
((BoundField)cell.ContainingField).DataField
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
remember that the code above will use a BoundField... then use it like:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "SomeOtherName");
string columnValue = e.Row.Cells[index].Text;
}
}

How to find a dynamic control (radio button) inside a placeholder in gridview

I have gridview with 4 columns; in column 1 I added a place holder and other 3 columns are boundfields. In column 1 I'm adding radio buttons dynamically using html code by which I am able to select only one radio button. It's working well, but the problem is I am unable to find the radio button control when a button outside of the gridview is clicked.
Please help, I've been stuck on this problem for 4 days.
Thank you in advance.
I used the following code
.aspx File
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" ForeColor="Black" GridLines="Vertical"
onrowdatabound="GridView1_RowDataBound"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="FIRST NAME" DataField="FNAME"/>
<asp:BoundField HeaderText="LAST NAME" DataField="LNAME"/>
<asp:BoundField HeaderText="EMAIL" DataField="EMAIL"/>
<asp:BoundField HeaderText="AGE" DataField="AGE"/>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:Button ID="btnSave" Text="Save" runat="server" onclick="btnSave_Click1" />
</form>
Code Behind file
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1 && e.Row.DataItem != null)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
RadioButton rb = new RadioButton();
rb.ID = "rbSelect";
holder.Controls.Add(rb);
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
PlaceHolder holder = (PlaceHolder)GridView1.Rows[i].Cells[0].FindControl("ph");
RadioButton rbtn = holder.FindControl("rb") as RadioButton;
if (rbtn.Checked == true)
{
Response.Write("<Script>alert('Radiocheck')</Script>");
}
}
}
It's not clear why you need to create dynamic RadioButtons at all. That makes all just more difficult without a benefit in this case(even if, a nested Repeater or GridView would be easier).
However,
you should not create dynamic controls in RowDataBound since that is triggered only if the GridView was databound. But since by default ViewState is enabled you wouldn't DataBind it on postbacks. Dynamic controls on the other hand must be recreated on every postback.
Therefore create them in RowCreated which is triggered on every postback. But note that you have (of course) no DataItem there since it is null at this stage(even if the grid will be databound).
So you should create cynamic controls in RowCreated but load them from RowDataBound where you can also access them (f.e. via FindControl).
But instead of adding html-control like <input type='radio' you should create and add a RadioButton with an id. Otherwise you won't be able to acess it later, so holder.FindControl("rb") will, be null since it's not a server-control.
Here's the complete modified code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
var rb = new RadioButton();
rb.ID = "RbSample";
rb.Text = "rb";
holder.Controls.Add(rb);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var rb = (RadioButton)e.Row.FindControl("RbSample");
rb.Checked = row.Field<bool>("SampleActive");
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rbtn = (RadioButton)GridView1.Rows[i].FindControl("RbSample");
if (rbtn.Checked)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Radiocheck');", true);
}
}
}
It looks like you are doing FindControl with the "value" of the input, but not with the ASP.NET ID of the control, because it has none. Because it's not an ASP.NET control you cannot find it with FindControl.
I also don't know if you can loop through the Controls property of holder, because it's a plain html control. But you can try it out to put a breakpoint on the FindControl line and explore the Controls property of holder.

Always getting checkbox as false in grid

i have checkboxes in a grid. I am trying to access them from codebehind and get the data for checked /unchecked rows.But even after the checkboxes being checked I am getting them as Checked property as false only:
Aspx:
<table width="100%">
<asp:GridView ID="grdRequestsPending" runat="server" Width="100%" AutoGenerateColumns="false"
BorderWidth="1px" BorderStyle="Solid" Style="margin-left: 0px" BorderColor="#ffcc00"
RowStyle-BorderColor="#ffcc00" RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px"
GridLines="Both" DataKeyNames="ReqID,ApproverComments" On="grdRequestsPending_ItemDataBound" OnRowDataBound="grdRequestsPending_RowDataBound"
OnPreRender="grdRequestsPending_PreRender">
<RowStyle CssClass="dbGrid_Table_row" />
<HeaderStyle CssClass="dbGrid_Table_Header" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblSelect" Text="Select All" runat="server"></asp:Label><br />
<asp:CheckBox ID="SelectAll" onclick="javascript:checkAllBoxes(this);" TextAlign="Left"
runat="server" />
</HeaderTemplate>
<ItemStyle Width="2%" />
<ItemTemplate>
<asp:CheckBox ID="chkReq" runat="server"/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="7%" />
</asp:TemplateField>
</Columns>
But when I am checking these I am always getting them as false in code behind:
protected void UpdateVMRequestStatusByCapSupLead(int StatusId)
{
try
{
DataTable dt = new DataTable();
dt.Columns.Add("ReqId", typeof(int));
dt.Columns.Add("StatusId", typeof(int));
dt.Columns.Add("ModifiedBy", typeof(string));
dt.Columns.Add("ModifiedDate", typeof(string));
dt.Columns.Add("txtCommentSupLead", typeof(string));
foreach (GridViewRow gr in grdRequestsPending.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("chkReq");
if (chk.Checked)
{
strReqId = strReqId + grdRequestsPending.DataKeys[gr.RowIndex].Value.ToString() + ',';
TextBox txtCommentSupLead = (TextBox)gr.FindControl("txtCommentSupLead");
dt.Rows.Add(dt.NewRow());
dt.Rows[dt.Rows.Count - 1]["ReqId"] = Convert.ToInt32(grdRequestsPending.DataKeys[gr.RowIndex].Value);
dt.Rows[dt.Rows.Count - 1]["StatusId"] = StatusId;
dt.Rows[dt.Rows.Count - 1]["ModifiedBy"] = Session["UserAccentureID"].ToString();
dt.Rows[dt.Rows.Count - 1]["txtCommentSupLead"] = txtCommentSupLead.Text;
dt.Rows[dt.Rows.Count - 1].AcceptChanges();
dt.Rows[dt.Rows.Count - 1].SetModified();
}
}
I am not getting the problem.I am gettign the control also correctly..
I assume that you're always databinding your GridView and not only if(!Page.IsPostBack)....
So put this in page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindControls(); // like GridView etc.
}
}
If you DataBind controls they will lose their changes and ViewState. Even events aren't triggered then. So you should do that only on the first load if EnableViewState="true".
Here is a simple example of populating a checkbox in a gridview and getting the values out on a button click
Default.aspx
<asp:GridView ID="gv"
runat="server"
AutoGenerateColumns="false"
OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkReq" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSubmit"
runat="server"
OnClick="btnSubmit_Click"
Text="Submit" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create 20 rows
gv.DataSource = Enumerable.Range(1, 20);
gv.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var isCheckedList = new List<bool>();
for(var index = 0; index < gv.Rows.Count; ++index)
{
var chkReq = (CheckBox)gv.Rows[index].FindControl("chkReq");
isCheckedList.Add(chkReq.Checked);
}
//Look at isCheckedList to get a list of current values.
System.Diagnostics.Debugger.Break();
}
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var index = e.Row.RowIndex;
//Strongly Bind Controls
var chkReq = (CheckBox)e.Row.FindControl("chkReq");
chkReq.Text = "Item " + index.ToString();
}
}
Since you did not show all of your code, it could be an issue like Tim Schmelter said or it could be something else. This example provides you with the basics that are needed to retrieve a checkbox value from a grid view.

Resources