change div display while checkbox checked in gridview using asp.net - c#

I have gridviewthat binded to database. There is checkbox in it that I want change display attribute of another div with checkbox checked value.
This is my back-end code in asp.net, but it isn't work! What can I do to solve it?
protected void gv_sourceGalleryPic_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "checkPic")
{
CheckBox chkItem = (CheckBox)gv_sourceGalleryPic.FindControl("ck_checkGalleryPic_copyMove");
if (chkItem.Checked == true)
{
div1.Style.Add(HtmlTextWriterStyle.Display, "block");
}
}
}

As i know, Asp.Net CheckBoxes do not have attributes named CommandName and CommandArgument. Therefore you can not use RowCommand event which is going to be fired when you change checked.
You should use some simple javascript codes instead of it like example code below:
function hidediv(chk) {
var element = document.getElementById("div1");
if (chk.checked)
{ element.style.display = 'none'; }
}
And then fire this function on change event of all checkboxes like this:
onchange="hidediv(this);"
By the way, if you want to change display a div section only, it would be better to use html input tag instead of asp.net checkbox.

You can use OnCheckedChanged event for checkbox instead onRowCommand like this:
Markup
<asp:GridView runat="server" ID="gv_sourceGalleryPic">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ck_checkGalleryPic_copyMove" runat="server"
OnCheckedChanged="chkBox_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void chkBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox;
if (chk.Checked)
{
div1.Style.Add(HtmlTextWriterStyle.Display, "block");
}
}

Try to find Div
HtmlGenericControl div1= (HtmlGenericControl )gv_sourceGalleryPic.FindControl("div1");

Related

RowDataBound not acting the way I expect

I have a Gridview with an ImageButton that should become visible for the selected row only. I'm doing this in the OnRowDataBound event, but it doesn't work.
protected void OnRowDataBoundMS(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
// some working code that handles the edit mode
}
else if (Gridview1.SelectedValue != null)
{
ImageButton ImgBut1 = e.Row.FindControl("ButtonUp") as ImageButton;
ImgBut1.Visible = true;
}
}
}
My gridview looks like this:
<asp:GridView runat="server"
ID="Gridview1"
DataSourceID="Milestones"
DataKeyNames="ID"
AutoGenerateColumns="false"
OnRowEditing="OnRowEditing"
OnRowDataBound="OnRowDataBoundMS"
OnSelectedIndexChanged="OnSelectedIndexChangedMS">
...
<asp:templatefield HeaderText="Order" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:ImageButton ID="ButtonUp" runat="server" OnClick ="OrderUp" ImageUrl="img/up.png" Visible="false"/>
</ItemTemplate>
</asp:templatefield>
I spent the last 3 hours on this and I start to freak out. Any hints on this? Martin
The other alternative is to use the SelectedIndexChanged event if you are using the Select command option:
protected void OnSelectedIndexChangedMS(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
Control ctl = row.FindControl("ButtonUp");
ctl.Visible = (row.RowState & DataControlRowState.Selected) != 0;
}
}
Something like that; RowDataBound may fire before the selected index gets updated (not sure about that...).
You can detect the selected row in the RowDataBound event handler with the RowState property, the same way you detect the edit row:
if ((e.Row.RowState & DataControlRowState.Selected) != 0)
{
...
}
An alternative is to set the Visible property of the ImageButton in the markup, with a data-binding expression:
<asp:ImageButton runat="server" Visible='<%# ((Container as GridViewRow).RowState & DataControlRowState.Selected) != 0 %>' ... />
Note: make sure that you call GridView1.DataBind() in the SelectedIndexChanged event handler, in order to refresh the content of the GridView.
I guess the key comment is what Brian Mains said about the RowDataBound firing before the selected Index gets updated. I can't prove this to be generally right, but it seems so. Therefore all attempts, even following ConnersFan suggestions didn't worked out. I did what Brian suggested and used the SelectedIndexChanged event handler, but without looping through all rows. The solution is actually quite simple:
protected void OnSelectedIndexChangedMS(object sender, EventArgs e)
{
Gridview1.DataBind();
ImageButton ImgBut1 = Gridview1.SelectedRow.FindControl("ButtonUp") as ImageButton;
ImgBut1.Visible = true;
}

How to get CheckBox value from GridView when CheckBox selected

I have GridView filled automatically as
<asp:GridView ID="gvValues" runat="server"
OnRowDataBound="gvValues_RowDataBound"
OnPageIndexChanging="gvValues_PageIndexChanging"
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<%# gvValues.PageSize*gvValues.PageIndex+ Container.DisplayIndex+1 %>
<asp:CheckBox ID="chkProduct" runat="server" CssClass="chkProduct"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="online" meta:resourcekey="Online">
<ItemTemplate >
<asp:CheckBox ID="chkProductonline" runat="server" OnCheckedChanged ="chkProductonline_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
What I need is when I click on the chkProductonline checkbox, to fire an event and get the chkProductonline and chkProducton values. I have tried this but it always gives me null.
protected void chkProductonline_CheckedChanged(object sender, EventArgs e)
{
var chkProductonline = FindControl("chkProductonline") as CheckBox;
// bool ischeck = chkProductonline.Checked;
var chkProduct = gvValues.FindControl("chkProduct") as CheckBox;
}
I can't loop the GridView. I need to do this one-by-one. Is there another way to do that?
You can try this:
protected void chkProductonline_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkProductonline = sender as CheckBox;
...
CheckBox chkProduct = chkProductionLine.NamingContainer.FindControl("chkProduct") as CheckBox;
...
}
You need to call FindControl on a specific row. You will not be able to call it on the entire GridView because there exists repeating content (i.e. multiple chkProductionlines and chkProducts). A row knows of its checkboxes, and not of the others.
So what you can do is first get the CheckBox that called the event (your sender parameter, chkProductionline) and use its NamingContainer. Since it is contained in a GridView row, cast the row as such as use it to find the other controls you may need.
protected void chkProductonline_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkProductionline = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkProductionline.NamingContainer;
CheckBox chkProduct = (CheckBox)row.FindControl("chkProduct");
}

Return Gridview Checkbox boolean

I've racked my brains on trying to access the ID column of a gridview where a user selects a checkbox:
<asp:GridView ID="gvUserFiles" runat="server">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The gridview columns are chkSelect (checkbox), Id, fileName, CreateDate
When a user checks a checkbox, and presses a button, i want to receive the "id" column value.
Here is my code for the button:
foreach (GridViewRow row in gvUserFiles.Rows)
{
var test1 = row.Cells[0].FindControl("chkSelect");
CheckBox cb = (CheckBox)(row.Cells[0].FindControl("chkSelect"));
//chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));
if (cb != null && cb.Checked)
{
bool test = true;
}
}
The cb.checked always is returned false.
The Checkboxes being always unchecked can be a problem of DataBinding. Be sure you are not DataBinding the GridView before the button click event is called. Sometimes people stick the DataBinding on the Page_load event and then it keeps DataBinding on every PostBack. As it is called before the button click, it can make direct influence.
When the GridView is DataBound you lose all the state that came from the page.
If you Databind the GridView on the Page_load, wrap it verifying !IsPostBack:
if (!IsPostBack)
{
gvUserFiles.DataSource = data;
gvUserFiles.DataBind();
}
If that is not your case, you can try verifying the checked property based on the Request.Form values:
protected void button_OnClick(object sender, EventArgs e)
{
foreach (GridViewRow row in gvUserFiles.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSelect");
if (cb != null)
{
bool ckbChecked = Request.Form[cb.UniqueID] == "on";
if (ckbChecked)
{
//do stuff
}
}
}
}
The Checked value of a CheckBox is sent by the browser as the value "on". And if it is not checked in the browser, nothing goes on the request.
You can achieve it using datakey like this
Add Datakey to your gridview
<asp:GridView ID="gvUserFiles" runat="server" DataKeyNames="Id">
and get it server side like this
string value = Convert.ToString(this.gvUserFiles.DataKeys[rowIndex]["Id"]);

Gridview event not firing

I have a requirement where i have to update a textbox if any of the value in my grid view changes.. I have a gridview with 2 rows ..
one a template field with label and another template field with a textbox...
my Grid view looks like
name value
a (empty textbox)
b (empty textbox)
c (empty textbox)
now when the user enters a value in teh text box it should automatically update another textbox which is linked to this.
Here my questions is when someone enters a value in the textbox an event should be fired!
(I am getting the names a,b,c, from database). i dont want to have an edit link or update link because all the values to be entered are mandatory!
i tried Grid_SelectedIndexChanged1 but this not firing.. is there something i am missing or i need to change so that the evant is fired and i can update the other textbox??
I am new to ASP.NET so please help!
Thanks in advance!
If the updates are supposed to be triggered when the text changes, you should use the OnTextChanged event of the TextBox, and set AutoPostBack to true.
EDIT
To avoid duplicating efforts here, using the above approach you can find the row index using the technique that Pankaj Garg outlined in his answer:
int rowIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex;
The biggest caveat to this approach is that it's not forgiving of changes in the markup. If you were to wrap the TextBox in another control that implements INamingContainer, the example above would break. For example:
<asp:TemplateField>
<asp:Panel ID="Panel1" runat="server"> <!-- becomes the naming container -->
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:Panel>
</asp:TemplateField>
That being said, you would want to notate your markup accordingly so other developers know to be careful when making changes.
EDIT
As an alternative, you could also trigger the postback in JavaScript using the onchange event of the TextBox:
<script type="text/javascript">
valueChanged = function(rowIndex){
__doPostBack("<%= GridView1.ClientID %>", rowIndex);
}
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:TemplateField>
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code-behind, override the RaisePostBackEvent method, and put your update logic there:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
int rowIndex = int.Parse(eventArgument);
TextBox txt = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
if (txt != null)
{
var id = (int)GridView1.DataKeys[rowIndex]["ID"];
var text = txt.Text.Trim();
//update the database
}
}
}
You can check the Current Row Index like below...
((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
Create a handler for OnTextChanged event and set the AutoPostBack Property True.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
int CurrentGridIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
}

Disabled checkboxes should not be checked when select all checkbox is clicked

I have a grid with a few items which have a checkbox at the start of each row. I also have a select all checkbox at the top of the grid. The scenario is something like our gmail or yahoo inbox. My question is, suppose i disable a checkbox and then click on select all checkbox, the disabled checkbox should not be checked. Is there any solution for this? I have attached relevant pieces of code as follows.
*aspx file
<telerik:GridTemplateColumn UniqueName="CheckBoxTemplateColumn">
<HeaderTemplate>
<asp:CheckBox id="headerChkbox" OnCheckedChanged="ToggleSelectedState" AutoPostBack="True" runat="server"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox id="CheckBox1" OnCheckedChanged="ToggleRowSelection" AutoPostBack="True" runat="server"></asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
*code behind
protected void ToggleRowSelection(object sender, EventArgs e) //selecting a particular row
{
((sender as CheckBox).NamingContainer as GridItem).Selected = (sender as CheckBox).Checked;
}
protected void ToggleSelectedState(object sender, EventArgs e) //select all rows
{
CheckBox headerCheckBox = (sender as CheckBox);
foreach (GridDataItem dataItem in grdCurrent.MasterTableView.Items)
{
(dataItem.FindControl("CheckBox1") as CheckBox).Checked = headerCheckBox.Checked;
dataItem.Selected = headerCheckBox.Checked;
}
}
You need to check if it is Enabled before setting it to Checked.
CheckBox headerCheckBox = (sender as CheckBox);
foreach (GridDataItem dataItem in grdCurrent.MasterTableView.Items)
{
if((dataItem.FindControl("CheckBox1") as CheckBox).Enabled) // add this condtion
{
(dataItem.FindControl("CheckBox1") as CheckBox).Checked = headerCheckBox.Checked;
dataItem.Selected = headerCheckBox.Checked;
}
}
Instead of using code behind to select all. I will use javascript or Jquery to do it. My method will be applying different css class for enabled and disabled checkbox like "enabled" and "disabled". In Jquery, I check the class and only tick the enabled checkboxes.

Categories