Conditionally Hide Checkbox in row of Gridview - c#

I'm having a ton of trouble and I've followed plenty of example codes from people with the same question. Basically I have a gridview and I have a column with checkboxes and another with a linkbutton. I want to hide/disable a checkbox in a row, if the databound linkbutton in the other column isn't null (field isn't empty). I've tried every way of doing this...(lb!=null), (lb.Text!=null) Also, I have tried finding the controls by Column Number...no luck
What am I doing wrong? (gridview functions normally other than the checkbox hiding feature)
I tried debugging and it seemed that it wasn't getting passed the first if statement (rowtype==...)
.cs:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButtonPO") as LinkButton;
if (lb.CommandArgument != null)
{
CheckBox cb = e.Row.FindControl("CbPO") as CheckBox;
if (cb != null)
cb.Visible = false;
}
}
}
.aspx
<asp:GridView ID="GridView1"
CssClass="Gridview" runat="server"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="Order_ID"
DataSourceID="OrderHistoryData"
HorizontalAlign="Center"
EmptyDataText="No Data to Display"
Width="785px"
AlternatingRowStyle-CssClass="alt" AllowPaging="True"
PagerStyle-CssClass="pager" GridLines="None" PageSize="20"
ShowHeaderWhenEmpty="True" OnRowDataBound="GridView1_RowDataBound">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonPO" runat="server" CommandArgument='<%# Bind("PO_ID") %>' OnClick="LinkButtonPO_Click" Text='<%# Bind("PO_Lit") %>'></asp:LinkButton>
</ItemTemplate>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="CbPO" runat="server" OnCheckedChanged="CbPO_CheckedChanged" Visible="true" />
</ItemTemplate>
</asp:TemplateField>

LinkButton.CommandArgument is implemented in this way(ILSpy on .NET 4):
public string CommandArgument
{
get
{
string text = (string)this.ViewState["CommandArgument"];
if (text != null)
{
return text;
}
return string.Empty;
}
set
{
this.ViewState["CommandArgument"] = value;
}
}
So as often in ASP.NET the property is never null but String.Empty.
So change
if (lb.CommandArgument != null)
cb.Visible = false;
to
cb.Visible = lb.CommandArgument.Length > 0;

I am using like this and works for me
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButtonPO") as LinkButton;
CheckBox cb = e.Row.FindControl("CbPO") as CheckBox;
if (cb != null)
{
cb.Visible = false;
}
}
}

You did not use Columns and Asp:TemplateField for Linkbutton So use that.

Related

DataGridView returning Null in cell while trying to display images in datagrid cells

I have two images in solution explorer at this location -
~/Images/Active.jpg & ~/Images/Inactive.jpg
I want to display these images in my gridview cell depending upon the cell value i.e "Active" or "Inactive".
What I have tried so far is given below:
Gridview code in page source file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnDataBound="GridView1_DataBound1" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:BoundField DataField="ServerName" HeaderText="ServerName" SortExpression="ServerName" />
<asp:BoundField DataField="Application" HeaderText="Application" SortExpression="Application" />
<asp:BoundField DataField="Instance" HeaderText="Instance" SortExpression="Instance" />
<asp:BoundField DataField="Environment" HeaderText="Environment" SortExpression="Environment" />
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgID" imageurl="" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Code behind .aspx.cs file:
foreach (GridViewRow row in GridView1.Rows)
{
if (row.Cells[4].Text == "Active")
{
Image img = (Image)row.FindControl("imgID");
img.ImageUrl= "";
}
else
{
Image img = (Image)row.FindControl("imgID");
img.ImageUrl = "~/Images/Inactive.jpeg";
}
}
Please note, I can not use rowdatabound. I have written above code in one of function where I am checking some stuff and updating cell values as Active or Inactive.
The problem arising is that DataGrid's Cell returning null value for images.
Please suggest solution to solve this.
Try:
foreach (GridViewRow row in GridView1.Rows)
{
Image img = (Image)row.FindControl("imgID");
if (img!=null)
{
img.ImageUrl= (row.Cells[4].Text == "Active") ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg";
}
}
You can bind your ImageURL using ternary operator:
ImageURL='<%# Eval("Status") == "Active" ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg" %>'
Note: Status is a value from your datasource.
Or, you can done same thing in your RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("imgID");
img.ImageURl = (e.Row.Cells[4].Text == "Active") ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg";
}
}
Thanks all for your answers. I solved issue with below change. its working fine now. :
if (answer.Contains("INACTIVE"))
{
row.Cells[4].Text = string.Format("<img src='Images/Inactive.jpg'; height='30' width='30' />");
}
else
{
row.Cells[4].Text = string.Format("<img src='Images/Active.jpg'; height='30' width='30' />");
}

Get data from dynamically created controls in TemplateFields for gridview

I have a webpage that has a gridview which is bound to a list of custom objects but also has 1 dynamically created TemplateFields. These fields are created at Page_PreRender and can be a textbox or dropdownlist based on the object in the list. I have a button at the bottom of the page that needs to save all the data inputed in the dynamic objects when pressed. When i try to find the dynamic control i am unable to do so using the FindControl() method. It always comes back blank.
How can i retrieve the user entered/selected data?
This is my gridview
<div id="divSearchCriteriaGrid" runat="server" class="padding-top-15">
<asp:GridView ID="gvSearchCriteria" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvSearchCriteria_OnRowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="SearchFieldId" Visible="False" />
<asp:TemplateField HeaderText="Search Field">
<ItemTemplate>
<asp:CheckBox ID="cbDisplay" runat="server" AutoPostBack="False" onclick="ToggleCriteriaControls(this)" />
</ItemTemplate>
<ItemStyle Width="25%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Begin Criteria">
<ItemStyle Width="35%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="End Criteria">
<ItemStyle Width="35%" />
</asp:TemplateField>
<asp:BoundField DataField="ControlTypeId" Visible="False" />
</Columns>
</asp:GridView>
</div>
And this is my code behind for creating the controls:
public void Page_PreRender(object sender, EventArgs e)
{
TryAction(PrepareLoad);
}
private void PrepareLoad()
{
if (IsPostBack) return;
BindData();
}
private void BindData()
{
gvSearchCriteria.DataSource = null;
gvSearchCriteria.DataSource = SearchFieldList;
gvSearchCriteria.DataBind();
}
protected void gvSearchCriteria_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SearchField searchField = e.Row.DataItem as SearchField;
if (searchField != null)
{
e.Row.Cells[0].Text = searchField.SearchFieldId.ToString();
e.Row.Cells[4].Text = searchField.ControlTypeId.ToString();
CheckBox checkBox = (CheckBox)e.Row.FindControl("cbDisplay");
checkBox.Text = searchField.FieldDescription;
checkBox.Checked = searchField.Checked;
checkBox.Enabled = true;
if (searchField.ControlTypeId.ToString() == "1")
{
RadTextBox textBox = new RadTextBox();
textBox.ID = "txtBoxBegin";
e.Row.Cells[2].Controls.Add(textBox);
textBox = new RadTextBox();
textBox.ID = string.Format("txt{0}End", searchField.SearchFieldId);
e.Row.Cells[3].Controls.Add(textBox);
}
else if (searchField.ControlTypeId.ToString() == "2")
{
RadComboBox comboBox = new RadComboBox();
comboBox = new SearchService().GetRadComboBoxById(searchField.SearchFieldId);
comboBox.ID = string.Format("cbo{0}Begin", searchField.SearchFieldId);
e.Row.Cells[2].Controls.Add(comboBox);
}
}
}
}
This all works good and the controls get created with the checkbox.
Here is my code for trying to loop through each row of the gridview to get the user entered data which does not work.
private void Save()
{
foreach (GridViewRow row in gvSearchCriteria.Rows)
{
CheckBox include = (CheckBox)row.FindControl("cbDisplay");
int id, controlTypeId;
string criteriaOne = string.Empty;
string criteriaTwo = string.Empty;
if (!include.Checked) continue;
id = int.Parse(row.Cells[0].Text);
if (controlTypeId == "1")
{
RadTextBox radTextBox = (RadTextBox) row.FindControl("txtBoxBegin");
if (radTextBox != null)
{
criteriaOne = radTextBox.Text;
}
radTextBox = (RadTextBox)row.FindControl("txtBoxEnd");
if (radTextBox != null)
{
criteriaTwo = radTextBox.Text;
}
}
else if(controlTypeId == "2")
{
RadComboBox radComboBox = (RadComboBox)row.FindControl(string.Format("cbo{0}Begin",id));
if (radComboBox != null)
{
criteriaOne = radComboBox.SelectedValue;
}
}
}
}
The radTextBox and radComboBox variables i am trying to get using the FindControlId always comes back null.
cell 0 comes back ok each time with the correct Id. the cbDisplay checkbox always returns whether the row is checked or not and cell 4 gets the ControlTypeId just fine. It is the TemplateFields that i cannot get the values for.
Any help is greatly appreciated.
I was able to get the information from the dynamic controls once i moved the BindData() function to the Page_Init instead of the Page_PreRender().

looping through gridview does not always work

Not sure what is causing this I have tried a few suggestions none seem to help. I have debugged my application dozens of times and the problem never occur while debugging everything steps through just fine. But when I publish my application and allow people to use it is when the problem occurs and it is not for everyone just randomly decides that a checkbox is not checked and skips the whole process also on the front end I have a validation that requires at least one checkbox to checked before the button_click will fire so I know that they had to have one checked.
Gridview
<div id="divEventDetail">
<asp:GridView ID="grdEventDetail" runat="server" AutoGenerateColumns="False" DataKeyNames="EDID" Width="381px" OnRowDataBound="grdEventDetail_RowDataBound" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="EventID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblEventID" runat="server" Text='<%# Eval("EDID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register" ItemStyle-CssClass="template-center">
<ItemTemplate >
<asp:CheckBox ID="chkRegister" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Wait List" ItemStyle-CssClass="template-center">
<ItemTemplate>
<asp:CheckBox ID="chkWaitList" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
CodeBehind
protected void registerEvent()
{
foreach (GridViewRow row in grdEventDetail.Rows)
{
CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;
if (chkR != null && chkW != null)// It is a datarow
{
GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);
if ((chkR.Checked) || (chkW.Checked))
// if ((((CheckBox)row.FindControl("chkRegister")).Checked == true) || (((CheckBox)row.FindControl("chkWaitList")).Checked == true))
{
Label eventID = row.FindControl("lblEventID") as Label;
***Then i do my database stuff here
I believe the grdEventDetail GridView doesn't have CheckBoxes in each row. For example, HeaderRow and FooterRow probably don't have those CheckBoxes.
I would rewrite the code to eliminate any error:
protected void registerEvent()
{
foreach (GridViewRow row in grdEventDetail.Rows)
{
CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;
if(chkR != null && chkW != null)// It is a datarow
{
GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);
if ((chkR.Checked) || (chkW.Checked))
{
//Your code goes here
}
}
}
}

how to search a control in an asp.net gridview and access it?

I have a gridview as :
<asp:GridView ID="gvAppRejProfiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Resumes
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnResumes" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i have a list of resume names (string format) that i want to add as the text of the linkbutton "lbtnResumes" for all the resume names that i have in a string array.
make use of FindControl() mehod ....to search control
void gvAppRejProfiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton bl =
(LinkButton)e.Row.FindControl("lbtnResumes");
}
}
for (int count = 0; count < gvAppRejProfiles.Rows.Count; count++)
{
LinkButton lbtnResumes = (LinkButton)gvAppRejProfiles.Rows[count].FindControl("lbtnResumes");
if (lbtnResumes.Text == "resume")
{
// Store and perform any operation
}
}

Programmatically access GridView columns and manipulate

I have a GridView :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" GridLines="None"
HorizontalAlign="Left" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowcommand="GridView1_RowCommand1">
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderStyle-Width="150">
<HeaderTemplate>
<b>Downloads</b>
</HeaderTemplate>
<ItemTemplate>
<!-- <asp:HyperLink ID="hyperlinkDownload" runat="server" NavigateUrl="" >Download
MP3</asp:HyperLink> -->
<asp:LinkButton CommandName="download"
CommandArgument='<%# Eval("Name") %>' runat="server">Download MP3</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
I want to query the value of a particular field in a DB and if it's true, display the LinkButton. if false, I want the linkButton not to be displayed.
is there a way to access the GridView programmatically and make visible certain of its columns or manipulate its items ?
help.
You can do this by adding a handler to the RowDataBound event. Add an event handler along this lines of this in your code behind:
protected void myGrid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
var data = e.Row.DataItem as DataRowView;
if (data != null)
{
var lbtDownload = e.Row.FindControl("lbtDownload");
lbtDownload.Visible = (bool) data.Row["HasFileForDownload"];
}
}
In your markup, attach the event handler to the grid:
<asp:GridView OnRowDataBound="myGrid_RowDataBound" ...>
You will also need to assign an id to the LinkButton, matching the one that you are search for using the FindControl() method in the event handler.
Disclaimer: I am on currently a Linux machine with no chance of testing this. Please report any bugs in the code - feel free to correct them if you have editor rights.
Yes there is.
1) You need to subscribe the RowDataBound event.
2) Give the LinkButton an ID.
3) Insert in codebehind
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _bt = e.Row.FindControl("ID") as LinkButton;
if(_bt != null)
{
// have a look at the e.row.DataItem and try to get the value of your desired visibility property
_bt.Visible = true;
}
}
}
4) If this does not work with accessing the DataItem, start thinking about a LinqDataSource.

Categories