I have an aspxGridView control to list some records. I am using a combobox to fill some data, which is different from aspxgridview's .
protected void ASPxGridView1_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (e.Column.FieldName == "LnkHotelID")
{
ASPxComboBox cmb = e.Editor as ASPxComboBox;
cmb.DataSource = DsHtel;
cmb.ValueField = "HotelID";
cmb.ValueType = typeof(Int32);
cmb.TextField = "HotelName";
cmb.DataBindItems();
}
}
I don't want to see "LnkHotelID" so I want it hidden. But when I hide this column, I can't use the function above. Also I want to see "HotelName" column but not to update it.
So I have two questions:
1) How can I access aspxcombobox at runtime?
2) How can I show my HotelName but not edit them?
Set the ASPxComboBox.ClientEnabled property to False:
ASPxComboBox cmb = e.Editor as ASPxComboBox;
cmb.ClientEnabled = false;
When you hide column with visible=false it will not render that in HTML so you can't use above function. So instead of visible false use style property with display: none
<style>
.hiddencolumn {display:none;}
</style>
<asp:GridView ID="GridViewHotel" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="LnkHotelID" ItemStyle-CssClass="hidden"
HeaderStyle-CssClass="hiddencolumn" />
</Columns>
</asp:GridView>
Now you can use your code.
Related
I am trying to hide a column in grid based on user role type
this is my c# code
protected void gvBudget_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (user == "1")
{
ImageButton imgBtn = (ImageButton)e.Row.FindControl("imgDelete");
imgBtn.Visible = false;
}
}
}
catch (Exception ex)
{
log.Info("Error in gvBudget_RowDataBound() " + ex.ToString());
}
}
this is the html page
<asp:TemplateField HeaderText="Delete" HeaderStyle-CssClass="grid_header_text">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="DEL" ImageUrl="~/Image/delete.gif"
OnClientClick="if(confirm('Budget List Summary \n\n Selected record will be deleted please confirm')==false){event.returnValue=false;return false;}else{return true;}" TabIndex="18" ToolTip="Delete" />
</ItemTemplate>
<HeaderStyle CssClass="grid_header_text"></HeaderStyle>
</asp:TemplateField>
i am able to hide the button, but unable to hide the row header or the column.
Based on your error message that you're logging, I am assuming that you have a GridView. If that is the case, couldn't something like this work?
gvBudget.Columns[0].Visible = false;
Ok, the problem is if we JUST hide the control, the column still renders. The key Rosetta stone here was that in fact your column control WAS hiding.
Say we have this:
And my code to hide the link button is say is this:
Dim lb As LinkButton = gv.FindControl("btnLNK")
lb.Visible = False
Then we get this:
So it DOES hide the control "in side" the column, but not the whole column.
So, you have to hide the cell, say like this:
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(4).Visible = False
End If
But note how his ONLY hide the data, not the header.
So we have to hide both header, and the data, say like this:
If e.Row.RowType = DataControlRowType.DataRow Or
e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells(4).Visible = False
End If
And we get this:
I am still a novice with asp.net, so I'm sure there are better ways to do some of this...
I want to allow a user to enter a date, and then execute an SQL query against a database to return all records matching that date. I want to display those records, and allow the user to select one for additional processing. It seemed like the DataGrid with a column of Pushbuttons was a good choice. In fact, I've done this before, but it those cases there was no user interaction involved. The page just ran a fixed SQL query. With what I'm doing now, the data is displayed as I want, but the Pushbuttons aren't working...the ItemCommand event doesn't fire.
I've read a lot of threads about the ItemCommand event not firing, but I still can't get this to work. My understanding is that I need to bind the DataGrid while not in a Postback, and I think my code does that. When I debug the Page_Load event, I can see that the code inside if (!IsPostBack){} is running, and the session variables have the expected data.
On the page that hosts the DataGrid, I have a 'Find' button that executes a SQL query against a database. The query uses a date entered into the textbox that is on that page. In the 'Find' button click event, I store the results of the query (a DataTable) in a session variable, then do a Redirect to re-load the page.
Once the page reloads, the session variables contain my expected data and the data is displayed in the DataGrid, along with the Pushbuttons. When I click any of the buttons in the DataGrid, the contents of the DataGrid disappear and the ItemCommand event does not fire.
Here's the definition of the DataGrid (updated to include the button):
<asp:Panel runat="server" ID="pnlSelect" HorizontalAlign="Left" Visible="true" style="margin-top:10px" >
Please select a participant.
<asp:DataGrid runat="server" ID="grdItems" AutoGenerateColumns="true" BorderColor="black" BorderWidth="1" CellPadding="3" style="margin-left:2px; margin-top:6px" OnItemCommand="grdSelect_ItemCommand" >
<Columns>
<asp:ButtonColumn HeaderStyle-HorizontalAlign="Center" ButtonType="PushButton" Text="Select" HeaderText="Select" CommandName="Select" >
<ItemStyle Width="60px" HorizontalAlign="Center"/>
</asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</asp:Panel>
Here's the Page Load code (unneeded code-behind stuff is commented out):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["y"] != null)
{
txtFind.Text = Session["x"].ToString();
DataTable table = Session["y"] as DataTable;
Session.Remove("x");
Session.Remove("y");
if (table != null)
{
/*
ButtonColumn buttonColumn = new ButtonColumn
{
HeaderText = "Select",
Text = "Select",
CommandName = "Select",
ButtonType = ButtonColumnType.PushButton,
};
grdItems.Columns.Add(buttonColumn);
foreach (DataColumn c in table.Columns)
{
BoundColumn column = new BoundColumn
{
HeaderText = c.Caption,
DataField = c.Caption,
ReadOnly = true
};
grdItems.Columns.Add(column);
}
*/
grdItems.DataSource = table;
grdItems.DataBind();
}
}
}
}
Here's the relevant 'Find' button event code. I can't post the details of the sql query text, but that part does work and the DataTable does contain the expected data:
DataTable table = DatabaseHelper.FindBySQL(sqlText);
if (table != null && table.Rows.Count > 0)
{
Session["x"] = searchtext;
Session["y"] = table;
Response.Redirect(Request.RawUrl, true);
}
And this the ItemCommand event. I place a breakpoint on the first line, and the debugger never hits it.
protected void grdItems_ItemCommand(object source, DataGridCommandEventArgs e)
{
string item = "";
switch (e.CommandName.ToLower())
{
case "select":
item = e.Item.Cells[1].Text.Trim();
//todo: handle the selected data
break;
}
}
Thanks for any thoughts.
Don
I have a datagridview name is "grdShowDeatils", a class with name "objShowCampaignStats" having method which returns a DataTable name of method is "GetCapmaignsStatsDetails()"
{
grdShowDeatils.DataSource = AnyDataTable;
}
My Problem is dataTable has three columns , i want to hide 2nd column at run time it should not be visible for user. How i can do this ?
Use this
{
grdShowDeatils.DataSource = objShowCampaignStats.GetCapmaignsStatsDetails();
grdShowDeatils.Columns[1].Visible = false;
}
You can write the following code
{
grdShowDeatils.DataSource = objShowCampaignStats.GetCapmaignsStatsDetails();
grdShowDeatils.Columns[3].Visible = false;
}
or
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
Suppose your DataTable returns below three columns ,
Name , Address , Phone No. And you want to hide Address Column
At .aspx page you can bind DataGridView as per the below,
<asp:DataGridView ID ="grdShowDeatils" runat="server">
<Columns>
<asp:BoundColumn HeaderText="Name" DataFeild="Name"/>
<asp:BoundColumn HeaderText="Address" DataFeild="Address" Visible = "False"/>
<asp:BoundColumn HeaderText="Phone No." DataFeild="PhoneNo"/>
</Columns>
</asp:DataGridView>
OR
You can code at RowDataBound event of DataGridView as per below,
protected void grdShowDeatils_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Rows.Cells[1].Visible = false;
}
I assume this is asp.Net Web Forms--can't you just set grdShowDeatils.autoGenerateColumns = "false" and then just specify the 1st and 3rd columns (via the designer or programmatically)?
I have a GridView with a DataSource (SQL Database). I want to hide a column, but still be able to access the value when I select the record. Can someone show me how to do this?
This is the column I want to hide and still want to access its value:
<asp:BoundField DataField="Outlook_ID" HeaderText="OutlookID" />
I tried everything to hide the column (property Visible="false"), but I can't access its value.
<head runat="server">
<title>Accessing GridView Hidden Column value </title>
<style type="text/css">
.hiddencol
{
display: none;
}
</style>
<asp:BoundField HeaderText="Email ID" DataField="EmailId" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
</asp:BoundField>
ArrayList EmailList = new ArrayList();
foreach (GridViewRow itemrow in gvEmployeeDetails.Rows)
{
EmailList.Add(itemrow.Cells[YourIndex].Text);
}
If I am not mistaken, GridView does not hold the values of BoundColumns that have the attribute visible="false". Two things you may do here, one (as explained in the answer from V4Vendetta) to use Datakeys. Or you can change your BoundColumn to a TemplateField. And in the ItemTemplate, add a control like Label, make its visibility false and give your value to that Label.
Define a style in css:
.hiddencol { display: none; }
Then add the ItemStyle-CssClass="hiddencol" and the HeaderStyle-CssClass="hiddencol" attribute to the grid field:
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" ClientIDMode="Static" />
You can use DataKeys for retrieving the value of such fields, because (as you said) when you set a normal BoundField as visible false you cannot get their value.
In the .aspx file set the GridView property
DataKeyNames = "Outlook_ID"
Now, in an event handler you can access the value of this key like so:
grid.DataKeys[rowIndex]["Outlook_ID"]
This will give you the id at the specified rowindex of the grid.
You can do it programmatically:
grid0.Columns[0].Visible = true;
grid0.DataSource = dt;
grid0.DataBind();
grid0.Columns[0].Visible = false;
In this way you set the column to visible before databinding, so the column is generated.
The you set the column to not visible, so it is not displayed.
If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:
<asp:TemplateField HeaderText="OutlookID">
<ItemTemplate>
<asp:Label ID="blah" runat="server">Existing Control</asp:Label>
<asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:
string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;
Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.
You can make the column hidden on the server side and for some reason this is different to doing it the aspx code. It can still be referenced as if it was visible. Just add this code to your OnDataBound event.
protected void gvSearchResults_DataBound(object sender, EventArgs e)
{
GridView gridView = (GridView)sender;
if (gridView.HeaderRow != null && gridView.HeaderRow.Cells.Count > 0)
{
gridView.HeaderRow.Cells[UserIdColumnIndex].Visible = false;
}
foreach (GridViewRow row in gvSearchResults.Rows)
{
row.Cells[UserIdColumnIndex].Visible = false;
}
}
Leave visible columns before filling the GridView. Fill the GridView and then hide the columns.
Here is how to get the value of a hidden column in a GridView that is set to Visible=False: add the data field in this case SpecialInstructions to the DataKeyNames property of the bound GridView , and access it this way.
txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")
That's it, it works every time very simple.
I have a new solution hide the column on client side using css or javascript or jquery.
.col0
{
display: none !important;
}
And in the aspx file where you add the column you should specify the CSS properties:
<asp:BoundField HeaderText="Address Key" DataField="Address_Id" ItemStyle-CssClass="col0" HeaderStyle-CssClass="col0" > </asp:BoundField>
I used a method similar to user496892:
SPBoundField hiddenField = new SPBoundField();
hiddenField.HeaderText = "Header";
hiddenField.DataField = "DataFieldName";
grid.Columns.Add(hiddenField);
grid.DataSource = myDataSource;
grid.DataBind();
hiddenField.Visible = false;
I found this solution, an elegant(IMO) quick 2 parter.
1.
On your gridview, add a column as normal, no need to do anything differently:
<asp:BoundField DataField="AccountHolderName" HeaderText="Account Holder"
ReadOnly="true"/>
You can keep the header text if this is useful to you for later processing.
2.
In the rowdatabound method for the grid hide the header, footer and row for that column index:
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[10].Visible = false;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[10].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[10].Visible = false;
}
You can do it code behind.
Set visible= false for columns after data binding .
After that you can again do visibility "true" in row_selection function from grid view .It will work!!
I searched a lot but no luck. The most of them was working with some errors. Finally I used this code and it worked for me.
probably you should change 1 to some other value. for me I would hide second col.
protected void FoundedDrGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType!=DataControlRowType.Pager)e.Row.Cells[1].Visible = false;
}
I just set the width to 0. and it works.
columns.AddFor(m => m.Id).Name("hide-id").Width(0);
When I want access some value from GridView before GridView was appears.
I have a BoundField and bind DataField nomally.
In RowDataBound event, I do some process in that event.
Before GridView was appears I write this:
protected void GridviewLecturer_PreRender(object sender, EventArgs e)
{
GridviewLecturer.Columns[0].Visible = false;
}
' />
I want to access the value in the hidden field in my code behind. I know i need to do this when the item is bound but i cant seem to work out how to do it.
protected void addLabelsWhereNeeded(object sender, EventArgs e)
{
// Get Value from hiddenfield
}
Try adding
OnRowDataBound="addLabelsWhereNeeded"
to your GridView. Then cast the control in the corresponding cell to a HiddenField to grab the value:
protected void addLabelsWhereNeeded(object sender, GridViewRowEventArgs e)
{
HiddenField hf = e.Row.Cells[0].Controls[1] as HiddenField;
String theValue = hf.Value;
}
assuming you've defined your GridView as:
<asp:GridView runat="server" ID="gv" OnRowDataBound="addLabelsWhereNeeded">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--your hidden field--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Just make sure you are indexing the correct cell and correct control within that cell.
yes you are right. You must do it on ItemDateBound. Check It must work
I do quite see what you want to achieve with this private field while databinding? In the RowDataBound Event you can access the whole data item, so there is no need for the use of a hidden value.
Pseudocode:
protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs)
{
if(e.RowType == RowType.DataRow)
{
}
}
Set a Breakpoint into if clause and use quickwatch to see how you need to cast the DataItem that is currently bound to gain full access to all properties, even if they aren't bound to any control.