RowDataBound not acting the way I expect - c#

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;
}

Related

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

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");

How to hide a link in a cell of a gridview?

I have a gridview which displays a data from the database. In one of the tables in this database have a column to store details about attanchment file. If the attachment is available that column value will set as "YES". Otherwise it will set as "NO". What I want to do is, show a link to view the attachment. But if cell value of the column is "NO" (when there is no attachment) the link must be hidden.
Note : I know how to view a file. Here what Im expecting is to hide the link in the cell which doesn't have an attachment.
This is what I have done upto now.
if (ds.Tables[0].Rows.Count > 0)
{
grdSo.DataSource = ds;
grdSo.DataBind();
for(int i=0; i <ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i][6].Equals("NO"))
{
grdSo.Rows[i].Cells[6].Visible = false;
}
else
{
grdSo.Rows[i].Cells[6].Visible = true;
}
}
}
I could hide the cell using this code. But unfortunately this hides the lines of the cell too. How can I avoid it happening?
One of the ways to do this is to use server side control like LinkButton to view the link that you want to show and set the visibility of the control as per your requirement in the OnRowDataBound event of the gridview.
Below is the code to show/hide LinkButton on OnRowDataBound event.
protected void gridId_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataSourceClass varData = (DataSourceClass)e.Row.DataItem;
// check if your data have flag to show the link
if(varData.show)
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = true;
else
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = false;
}
}
ASPX Code :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField Visible="false" DataField="id" />
<asp:TemplateField HeaderText="Has Attachment">
<ItemTemplate>
<asp:Label ID="lblAtt" runat="server" Text='<%#Eval("HasAtt") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Attachment">
<ItemTemplate>
<asp:LinkButton ID="lbtnAtt" runat="server" OnClick="lbtnAtt_Click" Visible="false">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Code :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
//Here you write databind logic
// Datasource table of GridView1 should contain 'HasAtt' and 'id' as its binded to label.
}
private void ViewAttachment(int id)
{
//Here you write your logic to view attachment.
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) // checking if row is datarow or not
{
Label lblHasAtt = e.Row.FindControl("lblAtt") as Label;
LinkButton lbtnViewAtt = e.Row.FindControl("lbtnAtt") as LinkButton;
lbtnViewAtt.Visible = (lblHasAtt.Text.ToLower() == "yes");
}
}
protected void lbtnAtt_Click(object sender, EventArgs e)
{
LinkButton lbtnViewAtt = sender as LinkButton;
GridViewRow grw = lbtnViewAtt.NamingContainer as GridViewRow;
int id = Convert.ToInt32(this.GridView1.Rows[grw.RowIndex].Cells[0].Text); // retriving value of first column on 'lbtnAtt' click row.
this.ViewAttachment(id);
}
I recall being able to parse through the grid view by using a for each for the rows and using a for statement for columns.
If I recall correctly, you can grab an item ie
row.Item[i]
foreach(GridViewRow row in GridView1.Rows)
{
for(int i = 0; i < GridView1.Columns.Count; i++)
{
// here you can do the logic to decide whether to show or hide the text for this cell
}
}
Sorry for formatting responding on my phone.

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"]);

How can I get the selected value from dropdownlist in edit mode of a gridview?

In my application, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList emailsListDL = (DropDownList)e.Row.FindControl("emailsDL");
emailsListDL.DataSource = allUsersEmails;//list of strings with the emails of the users
emailsListDL.DataBind();
}
}
}
But when I press the 'Update' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList emailsListDL = (DropDownList)GridViewAdvertisers.Rows[e.RowIndex].FindControl("emailsDL");
string email = emailsListDL.SelectedValue; //the selected value is every time the first value from the dropdownlist
}
Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck. I tried this:
1. emailsListDL.SelectedIndex = emailsListDL.Items.IndexOf(emailsListDL.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "OwnerMail").ToString()));
2. emailsListDL.SelectedValue = GridViewAdvertisers.DataKeys[e.Row.RowIndex]["OwnerMail"].ToString();
3. emailsListDL.SelectedValue = GridViewAdvertisers.Rows[e.Row.RowIndex].Cells[1].Text;
//ownerMail is a string (object) from the list of objects that I put as datasource to the gridview
Thanks,
Jeff
Update
My Item template from the aspx page is:
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="150px" HeaderText="Owner Email" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<asp:Label ID="LabelEmail" runat="server" Text='<%# Bind("OwnerMail")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="emailsDL" runat="server" Width="150">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="180px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
The SelectedIndex will always default to 0 if you don't define it in your DropDownList definition.
Edit: #Tim Schmelter should add his comment as an anwer. In the meantime, I'll paraphrase for other readers: You need to check for postback (see comments above).
You can declare a ComboBox mainBX = new Combobox();
and you can declare an event
private void onSeletedIndexChange(object sender,EventArgs e)
{
mainBX = (ComboBox)(sender);
}
and next you should iterate foreach ComboBox in GridView and Add this Event .
Than all you should do is ,take the mainBX.seletedItem();
I think this is what you need ,if not apologise .
To set the Selected Value in the RowDataBound-Event, you should do it like this:
(DropDownList)e.Row.Cells[/*index*/].Controls[/*index, or use FindControl*/]).Items.FindByValue(((DataRowView)e.Row.DataItem).Row.ItemArray[/*columnnumber*/].ToString()).Selected = true;
FindByValue finds the current Textvalue of the Field in the "normal" Viewmode and sets the DropDownList with the value.
Of course this needs to be encapsulated in
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
}
As for your "getting the Value at Update"-Problem, I must honestly say I've got no clue, since your approach is exactly like mine, only difference: mine works.
Here's my code if it's any help:
protected void gridVariables_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string control = ((DropDownList)gridVariables.Rows[e.RowIndex].Cells[3].Controls[1]).SelectedValue;
gridVariables.EditIndex = -1;
this.gridVariables_DataBind(control, e.RowIndex);
}
private void gridVariables_DataBind(string control, int index)
{
DataTable dt = (DataTable)Session["variableTable"]; //features a DataTable with the Contents of the Gridview
dt.Rows[index]["ControlType"] = control;
gridVariables.DataSource = dt;
gridVariables.DataBind();
}
I had the same problem with a different solution, I had implemented custom paging on the GridView with a custom pager, and in the process added the RowCommand method, which was rebinding the grid with a new page index. As it happens though the RowCommand method is also called during Updating.
So be sure to check any other locations you may be binding anywhere in your code.
Hope this helps somebody else.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string commandName = e.CommandName;
switch (commandName)
{
case "Page1":
HandlePageCommand(e);
//binding should happen here
break;
}
//this line is in the wrong location, causing the bug
BindGrid1();
}

Categories