I thought this would be an easy one for me to figure out (or atl east find someone online who has) but I am running into issues.
I have the following code that creates my gridview:
<asp:GridView runat="server" ID="ContactsGrid" AutoGenerateColumns="False" DataSourceID="LinqContact"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="ContactsGridView_RowDeleting" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="IConact_ID" Visible="false" ReadOnly="true" />
<asp:BoundField DataField="cFirstName" HeaderText="First Name" ReadOnly="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqContact" runat="server" ContextTypeName="TIPS.App_Data.TIPSDataContext" onselecting="LinqContact_Selecting" >
</asp:LinqDataSource>
Now on the c# side, I want to be able to pull the value from the first column (which is hidden) and use it to delete that specific record (with the onroedeleting event), but all the ways I found to pull the value, all come up null, like what would happen if I didn't have a LinqDatasource.
I have tried (and a slew of other that really didn't seem to be right, so not listed):
ContactsGrid.SelectedRow.Cells[0].Text;
ContactsGrid.Columns[0];
Thanks for any help!
Edit:
Ok, so I found that you can't get the value of a column this is hidden when you hide it using the grid. I did find a work around. If you hide the column using css instead, you can still access the colum.
<style type="text/css">
.hiddencol
{
display:none;
}
</style>
<asp:BoundField DataField="IContact_ID" ReadOnly="true" itemstyle-cssclass="hiddencol" />
I don't think that this is the prefered .net way. I found a reference to something called datakeynames which seems to be the proper way. I am going to dig into those next.
Edit #2:
I see that Maras and myself both came up with a solution for the hidden field, but I think I found the best one (cause its simple and built in).
In the gridview tag you can set the datakeynames attribute to your column (like a primary key, which is what I was storing in my hidden column) you can also store multiple columns.
<asp:GridView runat="server" ID="ContactsGrid" AutoGenerateColumns="False" DataSourceID="LinqContact" DataKeyNames="IContact_ID"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="ContactsGridView_RowDeleting" >
you can then reference it with:
ContactsGrid.DataKeys[e.RowIndex].Value;
Try this:
void ContactsGrid_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
ContactsGrid.Rows[e.RowIndex].Cells[0];
}
See here for more details http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdeleting.aspx#Y200
.
Edit after author's comment:
If you set it visibility to 'false' then there is nothing your browser can send you back in postback. You can use hidden field like in the second example:
<asp:GridView runat="server" ID="gv" OnRowDeleting="gv_RowDeleting" AutoGenerateColumns="false" AutoGenerateDeleteButton="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hf" runat="server" Value="<%# ((YourItemType)Container.DataItem).Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
HiddenField hf = (HiddenField) gv.Rows[e.RowIndex].Cells[0].FindControl("hf");
}
Related
I have a gridview binded to a datasource.
<asp:GridView ID="DocumentReviewGrid" runat="server" AllowPaging="True" AllowSorting="True"
EnableModelValidation="True" Width="100%" BorderStyle="None"
CssClass="docnav_data" BorderWidth="1px" GridLines="None" DataSourceID="DocumentReviewDataSource"
HorizontalAlign="Left" OnRowDataBound="DocumentReviewGrid_RowDataBound"
OnRowCreated="DocumentReviewGrid_RowCreated" CellSpacing="5"
PageSize="20" OnPageIndexChanged="DocumentReviewGrid_PageIndexChanged">
<AlternatingRowStyle BackColor="#EBF2F9" BorderStyle="None" />
<FooterStyle HorizontalAlign="Left" />
<HeaderStyle BackColor="#E7E7E7" HorizontalAlign="Left" />
<PagerSettings Mode="NumericFirstLast" Position="Top" PageButtonCount="4" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
As you can see Autogenerated Column is set to true, and it must be kept like that. One of the column is a SQL bit value, so it's represented as checkbox. I would like to be able to edit the checkbox column only, without using "AutoGenerateEditButton" property. I would just like to:
be able to check/uncheck the checkbox (I am stuck here)
performing a single update using an external button
the other columns must be readonly
Autogenerated columns cannot be manipulated directly in pretty much anyway, so there is no simple way to do it. So what you could do is create a custom column, which will always come first before any auto generated columns (again, this behavior cannot be changed), and hide the auto generated bit column.
How to hide the column is described here. Essentially you cannot use Columns collection, so need to do this:
protected void DocumentReviewGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[X].Visible = false; // hides the first column
}
Here X is the 0-based index of the column to hide.
And now to prepend the column just define it the way you want, leaving AutoGenerateColumns="true":
<asp:GridView ID="DocumentReviewGrid"...>
<Columns>
<asp:CheckBoxField HeaderText="Esclusione" DataField="Esclusione" />
</Columns>
</asp:GridView>
Admittedly this is quite hackish, but that will get you almost where you want - bool column displayed and editable.
I have a grid view, in which I have 1 column as template field, while other 8 columns are dynamically created.
This template field has a checkbox, while trying to retrieve this checkbox in code-behind file, we get it as null.
When columns are not dynamically created, the checkbox is pretty fine and has a value in code behind.
Below is my code:
<asp:GridView ID="gridResultSet" runat="server" AutoGenerateColumns="false" AllowSorting="true"
OnRowCreated="GridResultSet_RowCreated" OnLoad="GridResultSet_Load" CssClass="reportGrid"
CellPadding="4" OnSorting="GridResultSet_Sorting" OnRowDataBound="GridResultSet_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Reclass">
<ItemTemplate>
<acesec:CheckBox ID="chkReclass" CssClass="CheckBoxListStyle" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="gridrow" />
<AlternatingRowStyle CssClass="gridrow" />
<HeaderStyle CssClass="gridheader" />
</asp:GridView>
System.Web.UI.WebControls.CheckBox chbReclass = gridResultSet.Rows[i].FindControl("chkReclass") as System.Web.UI.WebControls.CheckBox;
Do I need to check something in order to access a template field while creation of dynamic columns?
Any body faced same kind of situation?
Pointers will be highly appreciated.
Regards
I have a fairly simple asp grid view, tied to an object data source. What I want to have is this gridview update on a button click with results that a dynamic depending on the value within a textbox (it's the basis for a search screen).
So far, everything works as such:
ASPX File:
<h3>Search Parameters</h3>
<div>
Account Name
<asp:TextBox runat="server" ID="AccountName"></asp:TextBox>
</div>
<asp:Button ID="Search" runat="server" Text="Search" OnClick="Search_Click" />
<asp:GridView runat="server" ID="SearchGrid" DataSourceID="ObjectDataSource1" AutoGenerateColumns="False" Width="100%" AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None" >
<Columns>
<asp:BoundField DataField="PartyID" HeaderText="Party ID" SortExpression="PartyID" />
<asp:BoundField DataField="PartyName" HeaderText="Party Name" SortExpression="PartyName" />
<asp:BoundField DataField="CompleteAddress" HeaderText="Address" SortExpression="CompleteAddress" />
</Columns>
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="DIS.Data.DataSetAccountsTableAdapters.GetAccountsBySearchParametersTableAdapter">
<SelectParameters>
<asp:Parameter Name="PartyName" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
ASPX.CS File:
protected void Search_Click(object sender, EventArgs e)
{
ObjectDataSource1.SelectParameters["PartyName"].DefaultValue = AccountName.Text;
}
At face value, everything works. The user enters text into the account name box, hits search, and the grid view is updated with the appropriate values.
The problem occurs when we get enough row to generate paging. The page links are shown on the GridView, but clicking on them has no effect at all - The values will remain consistently on page 1.
I believe that it may be something to do with the postback when the page link is clicked, but unfortunately my knowledge in this area is not strong enough to actually diagnose what exactly is happening.
Any help would be greatly appreciated
Best regards
OK, on further testing it doesn't appear to be a GridView specific issue.
We aer also using JQuery mobile, and it seems that it's those scripts that are causing the issue. Disabling them removed the problem.
I would like the rows of my GridView to have strikethrough based on a bound data value called IsObsolete. I tried to do this:
<RowStyle BackColor="#EFF3FB" Font-Strikeout='<%# Bind('IsObsolete') %>' />
But obviously this doesn't parse. I'd rather not do this in GridView.DataBound(). Any other ideas?
I do this by applying a style on the DataBinding event of one of my controls in a template. Example:
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="SomeTitle">
<ItemTemplate>
<asp:HyperLink ID="hrefYourLink" runat="server"
NavigateUrl="Somepage.aspx?id={0}"
OnDataBinding="hrefYourLink_DataBinding"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then implement the OnDataBinding event:
protected void hrefYourLink_DataBinding(object sender, System.EventArgs e)
{
HyperLink link = (HyperLink)(sender);
GridViewRow row = (GridViewRow)(link.Parent.Parent);
if ((bool)(Eval("IsObsolete"))
{
row.CssClass = "StrikeThroughStyle";
}
link.Text = HttpUtility.HtmlEncode(((int)(Eval("ID"))).ToString());
link.NavigateUrl = string.Format(link.NavigateUrl, Eval("ID").ToString());
}
This is just an quick example with a column with a link that gets modified based on the databinding as well but you should be able to get the gist of if an tweak it to suit your needs. I like doing it on the databinding because I do no binding inline in my aspx code.
Since the RowStyle element is applicable to the entire grid, the only way to accomplish what you want would be to have TemplateItems set for all columns and apply a CssClass to each column based on that same data value.
I'm not sure for your reasoning for avoiding the DataBound event for doing this as that would be the simplest way to accomplish it.
You might also try using a formatting function and itemstyles. Stealing a tidbit of code from above and changing it:
<%
public string GetObsoleteClass(string obsolete)
{
bool obs = Convert.ToBoolean(obsolete);
obs ? return "myObsoleteClass" : return "myNotObsoleteClass";
}
%>
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="SomeTitle">
<ItemTemplate>
<asp:HyperLink ID="hrefYourLink" runat="server"
NavigateUrl="Somepage.aspx?id={0}"
OnDataBinding="hrefYourLink_DataBinding"></asp:HyperLink>
</ItemTemplate>
<itemstyle CssClass='<%# Eval("isObsolete") %>'>
</itemstyle>
</asp:TemplateField>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
<itemstyle CssClass='<%# Eval("isObsolete") %>'>
</itemstyle>
</asp:boundfield>
</Columns>
</asp:GridView>
I have an ASP.NET GridView that just won't sort! I'm sure that I am missing something pretty obvious.
Page.aspx
<asp:GridView ID="TimeAwayGridView" runat="server" AutoGenerateSelectButton="False"
AutoGenerateEditButton="False" AutoGenerateDeleteButton="False" AllowPaging="False"
AllowSorting="True" CssClass="gridview" OnSorting="TimeAwayGridView_Sorting">
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Hours" HeaderText="Hours" SortExpression="Hours" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
Page.aspx.cs
protected void TimeAwayGridView_Sorting(object sender, GridViewSortEventArgs e)
{
}
Asp.Net Datagrip provides you with sorting event, and name of the column that was clicked in GridViewSortEventArgs, but you have to provide you own sort implementation in TimeAwayGridView_Sorting function. Meaning you should sort your datasource and rebind the datagrid.