How to hide a column but still access its value? - c#

I have a gridview, with some columns. I want to hide one column, but still access its value when I select a record.
Could someone help me to achieve this?
Any Help is appreciated.
This is my gridview: OutlookID is the column to hide!
<asp:GridView ID="gvOutlookMeldingen" runat="server"
AllowSorting="True" AutoGenerateColumns="False"
AutoGenerateSelectButton="True" onselectedindexchanged="GridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Melder" HeaderText="Melder" />
<asp:BoundField DataField="Onderwerp" HeaderText="Onderwerp" />
<asp:TemplateField HeaderText="Omschrijving">
<ItemTemplate>
<div style="overflow:auto; width: 500px; height: 150px;">
<asp:Label ID="lblOmschrijving" runat="server" Text='<%# Bind("Omschrijving")%>'></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Meldingsdatum" HeaderText="Meldingsdatum" />
<asp:BoundField DataField="OutlookID" HeaderText="OutlookID" Visible="false" />
</Columns>
</asp:GridView>
This is the code when I select a record:
Label lblOmschrijving = (Label)gvOutlookMeldingen.SelectedRow.FindControl("lblOmschrijving");
//Label lblOutlookID = (Label)gvOutlookMeldingen.SelectedRow.FindControl("lblOutlookID");
Response.Redirect("Detailscherm.aspx?"
+ "melder=" + Server.UrlEncode(gvOutlookMeldingen.SelectedRow.Cells[1].Text)
+ "&meldingsdatum=" + gvOutlookMeldingen.SelectedRow.Cells[4].Text
+ "&onderwerp=" + Server.UrlEncode(gvOutlookMeldingen.SelectedRow.Cells[2].Text)
+ "&outlookid=" + Server.UrlEncode(gvOutlookMeldingen.SelectedRow.Cells[5].Text)
+ "&omschrijving=" + Server.UrlEncode(lblOmschrijving.Text)
+ "&niv1=" + ""
+ "&niv2=" + "");

Set this code after you've binded the data. To get this functionality I do this:
MyGridView.Columns[0].visible = true;
MyGridView.DataBind();
MyGridView.Columns[0].visible = false;
With this the first column is hidden, but you should be able to acces it's value.

If you don't want the data to be available on the client side, you'll have to set the server-side Visible = "False" property of whatever DataControlField you're using (preferably in the markup). You'll still be able to access the column from the server side.
You might want to consider using the GridView's DataKeys property - it might be more suited to your needs.

Create Template column instead of your SELECT button. Set
PostbackUrl='<%#
Eval("somepage.aspx?id={0}","wanted
column") %>'
. Remove column via designer.

You can also set it invisible at the client side. With Javascript.
document.getElementById(myObject).visible = "false";

when we set visiblity of control false in Design time that will be not render .Try to
set visiblity =false in gridView rowCreated Event .in below code i am setting
second column visibility= false
protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Visible = false;
}
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[2].Visible = false;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[2].Visible = false;
}
}
and now try to Get Value .Surely you will get the value.

I had the same issue.
You can't hide the column and keep value in code behind.
You have to hide it directly on client side with a javascript.
I did that :
On my css or page :
<style type="text/css">
.hiddencol
{
display: none;
}
.viscol
{
display: block;
}
</style>
Then add style into the BoundField of the gridViewer.
For example :
<asp:BoundField DataField="AgentGUID" HeaderText="AgentGUID" ReadOnly="True" SortExpression="AgentGUID"
meta:resourcekey="BoundFieldResource1">
<HeaderStyle CssClass="hiddencol" />
<ItemStyle CssClass="hiddencol" />
<FooterStyle CssClass="hiddencol" />
</asp:BoundField>

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' />");
}

Gridview column linkbutton change the value according to data

I am trying to complete a simple task;
a gridview column gets an integer data if integer is equals to zero print "active" and set the commandname of the linkbutton to active else set linkbutton text and command value to inactive.
here is what I have so far
<Columns>
<asp:BoundField HeaderText = "User Name" DataField="UserName"
HeaderStyle-Width="16%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText = "Role" DataField="RoleNAME"
HeaderStyle-Width="14%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText = "Group" DataField="GroupName"
HeaderStyle-Width="12%" ItemStyle-HorizontalAlign="Center" />
<asp:ButtonField ButtonType="link" CommandName = "Active"
HeaderText="Status" Text="Active"
HeaderStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:ButtonField ButtonType="link" CommandName = "Edit"
HeaderText="" Text="Edit/View"
HeaderStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
</Columns>
codebehind
protected void grdMyQueue_RowdataBound(object sender, GridViewRowEventArgs e)
{
// In template column,
if (e.Row.RowType == DataControlRowType.DataRow)
{
var obj = (User)e.Row.DataItem;
if (obj.isDisabled == 0)
{
LinkButton linkButton = new LinkButton();
linkButton.Text = "Active";
linkButton.Enabled = true;
linkButton.CommandName = "Active";
//linkButton.CommandArgument = e.Row. //this might be causing the problem
e.Row.Cells[3].Controls.Clear();
e.Row.Cells[3].Controls.Add(linkButton);
}
else
{
LinkButton linkButton = new LinkButton();
linkButton.Text = "InActive";
linkButton.Enabled = true;
linkButton.CommandName = "InActive";
e.Row.Cells[3].Controls.Add(linkButton);
}
}
}
However when I Click the active linkbutton on the cell I get an error at onrowcommand function
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument); // this is the error line
GridViewRow gvRow = userManager.Rows[index];
TableCell usrName = gvRow.Cells[0];
string userName = usrName.Text;
....
How can I manage to change LinkButton text and CommandName depending on that integer data?
P.S I tried Eval but I couldnt figure out whats going on....
I would simply return the data from your data source, as intended. Then I would use an Update Panel to avoid the Postback that will occur from your Link Button. As for the text modifying I would use Javascript, so Javascript will read the page on the client. So when your data source returns:
One
One
Two
One
The Javascript can analyze those rows, then modify the internal cell within the Grid quite painless.
An example of Javascript:
$(".Activator").each(function () {
if ($(this).prev().find(':checkbox').prop('checked')) {
$(this).text("Deactivate");
}
});
This example will validate if a checkbox is checked, if it is modify the internal text to the class .Activator.
Then the internal item in the Grid for code on front-end would look like:
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox
ID="CustomerCheck" runat="server"
Checked='<%# Eval("Active") %>'
Enabled="false" />
<asp:LinkButton
ID="lbCustomerActive" runat="server"
Text="Activate"
CommandName="OnActivate"
ToolTip='<%# "Activate or Deactivate Course: " + Eval("CourseID") %>'
OnClick="CustomerCheck_Click"
CssClass="Activator">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
As you can see, as the internal data is changed the Javascript will automatically adjust the value for me every time the Data Source is binded again. Which the CustomerCheck_Click would execute the code on the server, which will read the Command Argument which contains the Row Id. Which will Update that particular record without a problem and rebind the Grid. (Partially lied, I'm parsing the Tooltip).
You would instantiate on server side like:
((LinkButton)sender).ToolTip;

grid_selectedindexchanged problem

//code in aspx file:
<html>
<body>
<form>
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="False"
onselectedindexchanged="grid_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RollID" HeaderText="RollID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
</asp:GridView>
</div><br />
<asp:label ID="Label" runat="server" text=""></asp:label>
</form>
</body>
</html>
//code behind file:
protected void grid_SelectedIndexChanged(object sender, GridViewRowEventArgs e)
{
RowIndex = grid.SelectedIndex;
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
!!! The question is,though iam able to print the data in the grid view form,but when i select a row,i could not print out the message"You selected..etc.." with the use of "Label" server control.
"could any1 plz sort m out dis issue"...
Don't use the SelectedIndexChanged event. Instead, use the RowCommand event:
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
int RowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
}
MSDN Link: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
How are you selecting a row? You may want to set this attribute on the gridview to allow selection to even take place (that the gridview is aware of) by allowing the control to generate a button:
AutoGenerateSelectButton="True"
You can see more information about this here. Of course, this isn't the only way to create a command button, but you'll have to followup if it won't suit your purposes.

How do I edit data being bound to a datagrid?

In reference to Link loaded into my gridview try to navigate to my local server. The columns I have in the datagrid are Customer #, Description, Link.
I've got a function set up that's called on rowDataBound, but how do I retrieve what link is in the row so that I can edit it, and then rebind it to the datagrid?
protected void grdLinks_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowIndex == 2 )
{
}
}
And here is my gridview code
<asp:GridView ID="grdLinks" runat="server" AutoGenerateColumns="False" DataSourceID="ldsCustomerLinks"
OnRowDataBound="grdLinks_RowDataBound" EmptyDataText="No data was returned."
DataKeyNames="ID" OnRowDeleted="grdLinks_RowDeleted" Width="80%" BackColor="White"
HorizontalAlign="Center" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<Columns>
<asp:BoundField DataField="CustomerNumber" HeaderText="Customer Number" SortExpression="CustomerNumber" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:HyperLinkField DataTextField="Link" HeaderText="Link" SortExpression="Link" DataNavigateUrlFields="Link" Target="_blank" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="ldsCustomerLinks" runat="server" ContextTypeName="ComplianceDataContext"
TableName="CustomerLinks" EnableDelete="true">
</asp:LinqDataSource>
If I'm understanding you correctly, you want to get the value of a data item called Link. If so, then something like this should work:
EDIT: I think what you're saying is that you want to grab the value Link from the database, manipulate it and then set the Url of the HyperLink to the new, manipulated value, if so then it would look like this:
ASPX Page (Updated to reflect posted code)
<Columns>
<asp:BoundField DataField="CustomerNumber" HeaderText="Customer Number" SortExpression="CustomerNumber" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:HyperLink ID="hlParent" runat="server" Text='<% #(Eval("Link")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
I modified the ASP from your original question by adding an ID and removing the reference to the NavigateUrl attribute from the HyperLink control.
Code
protected void grdLinks_RowDataBound( object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string link = DataBinder.Eval(e.Row.DataItem, "Link") as string;
if (link != null && link.Length > 0)
{
// "FindControl" borrowed directly from DOK
HyperLink hlParent = (HyperLink)e.Row.FindControl("hlParent");
if (hlParent != null)
{
// Do some manipulation of the link value
string newLink = "https://" + link
// Set the Url of the HyperLink
hlParent.NavigateUrl = newLink;
}
}
}
}
RowDataBound is called for every row in the GridView, including headers, footers, etc. Therefore, you should start by examining only the rows containing data.
Once you're on a row, there are several ways to examine the cells. One is just to use the cell index (2 here). That seems simple in your situation, but will lead to frustration if you ever rearrange the columns.
Here's an example of that from MSDN:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
A better way is to use FindControl with the item's ID.
protected void gvBarcode_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlParent = (HyperLink)e.Row.FindControl("hlParent");
}
}
You may also want to look into letting the gridview do it for you.
You can use the datanavigateurlformatstring property to insert querystring parameters if that's what you are trying to do.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.datanavigateurlformatstring.aspx

how to check status of checkboxes in gridview columns on click of button

T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box").
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
I found the answer. and its working...
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
and girdview code is...
<asp:BoundField ItemStyle-Width ="100px" DataField ="EventStartDate" DataFormatString ="{0:g}" HeaderText ="<%$ Resources:stringsRes, ctl_EventList_StartDate %>" SortExpression ="EventStartDate" HtmlEncode ="true" ItemStyle-Wrap ="false" />
<asp:BoundField ItemStyle-Width="100px" DataField="EventDate" DataFormatString="{0:g}" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Date %>" SortExpression="EventDate" HtmlEncode="true" ItemStyle-Wrap="false" />
<asp:ButtonField ItemStyle-Width="150px" ButtonType="Link" DataTextField="EventName" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Event %>" SortExpression="EventName" CommandName="show_details" CausesValidation="false" />
<asp:BoundField DataField="EventLocation" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Location %>" SortExpression="EventLocation" />
<asp:TemplateField HeaderText ="Select">
<ItemTemplate >
<asp:CheckBox ID="chkDownloadSelectedEvent" runat ="server" AutoPostBack ="false" Onclick="eachCheck();"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
and there is a link button ....
I havnt used the checkbox in grid view but would you not do a for loop around the columns in gridview and check the state? Myabe add a count and if 0 then alert.
var grid = document.getElementById("gridId"); //Retrieve the grid
var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
var isValid = false;
for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
isValid = true;
break;
}
}
}
if(!isValid) {
alert('Check at least one checkbox');
}

Categories