I am using asp.net and I'm working with a gridview. I have one of the fields in my GridView set up as a HyperLinkField that represents the name of the category. I pull the name and Id from a database and I can never be sure what they are because they are added separately. I want to be able to pass a changing CategoryId to another page through the query string. How can I do this with a GridView?
In your Hyperlink field, set the DataNavigateUrlFields to your ID column and set the DataNavigateUrlFormatString to the Url to navigate to (where {0} will be replaced by ID)
<asp:HyperLinkField
DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="Target.aspx?ID={0}"
DataTextField="Name"
Target="_blank">
</asp:HyperLinkField>
You can do it by using a <asp:TemplateField /> as one of your columns instead of a <asp:BoundField />
Code example:
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Container.DataItem("name")
</ItemTemplate>
</asp:TemplateField>
There might be a cleaner way of doing this rather than using the anchor element, but you should get the idea.
Related
I have one GridView in a .aspx page, and am showing dynamic data in this grid, setting AutoGenerateColumns="True".
Depending upon which of the options the user selects in a combo box, I am binding different DataTables to the GridView. For example, if the user selects Persons then I am fetching the Persons DataTable, and if the user selects Products then I am fetching Products DataTable.
How can I show a float or double number in 2 decimal places in GridView?
The bound column should have a DataFormatString column. You could do something like:
DataFormatString="{0:0.00}"
Numeric Custom Format Strings
UPDATE
In the case of AutoGenerateColumns="true"... I'd have to know more specifics about what you're binding, but here are some avenues to explore:
I'm not sure if GridView will
respect the DataFormatAttribute in
Data Annotations. If you are binding
an object, and GridView respects
that attribute, that might be one
route to go.
Wire the RowDataBound event and
inspect each column for potential
decimal values, and format that way.
you can write BoundField in GridView:
<asp:BoundField DataField="amount" DataFormatString="{0:n}" />
you can also write TemplateField in GridView
<asp:TemplateField>
<ItemTemplate>
<%#Eval("amount","{0:n}")%>
</ItemTemplate>
</asp:TemplateField>
You can do DataFormatString="{0:n2}"in your boundfield
This works on a template column, say if you want a decimal out to two places for a ratio (like 1:3)
<%# Eval("somedatacolumn", "1:{0:.##}").ToString() %>
If you use DataFormatString and it does not seem to be doing the trick, add HtmlEncode = "false", for example:
<asp:BoundField DataField="DateScheduled" HeaderText="Date Created" DataFormatString="{0:D}" HtmlEncode="false"/> // date format
<asp:BoundField DataField="Amount" HeaderText="Pay This Amount" DataFormatString="{0:F}" HtmlEncode="false"/> // number format
There are two easy ways to format things in a GridView. The first is given in a previous answer - use the DataFormatString. The second, which sounds like it applies to your situation, where you are dynamically loading the grid, is to change the data going into the grid.
So, rather than returning a number and trying to format it, return a formatted number and let the GridView display it.
<asp:TemplateField HeaderText="Prev Salary" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblGrdSalary" runat="server" Text='<%#Bind("Salary", "{0:n}") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="70px" />
</asp:TemplateField>
I have a master-detail page, in which I use GridView to display multiple rows of data, and DetailsView + jQuery dialog to display the details of a single records. only one DetailsView is open at a time.
I need to be able to pull out a single field of the open DetailsView, for manipulation using JavaScript. Is there a way to give a unique ID to a given field in DetailsView, so I can use getElementByID? Or is there another way to accomplish what I'm trying to do?
Thank you in advance.
If you are using a bound textbox in a template field in your detailsview you can then select it by:
$("[id$='MyTextBox']");
Which will find the textbox bound to MyFieldName as below.
<asp:DetailsView ID="DetailsView1" runat="server">
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MyTextBox" Text='<%# Bind("MyFieldName")%>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Whatever guff asp.net adds onto the begining of the id won't matter because jQuery $= mean "ends with".
there may be a better way, but when I've needed an id available for js work, I just convert the bound field to a templated field. you can then give the textbox the id of your choice. keep in mind when rendered the id will be expanded with the id of the parent control.
I want to output a list of news headlines that are clickable. So far I can get it to print out a list of headlines because I dragged and dropped the NewsHeadline table in designer view in VS 2010. How do you think I should the make the list elements clickable? I looked for a URL attribute but I did not see it. Do I need to wrap in a < a href ?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="NewsHeadline" HeaderText="NewsHeadline"
SortExpression="NewsHeadline" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>"
SelectCommand="SELECT [NewsHeadline] FROM [NewsTable]"></asp:SqlDataSource>
</form>
You need to change the column type from a BoundColumn to a Hyperlink column.
<asp:hyperlinkfield headertext="NewsHeadline"
datatextfield="NewsHeadline"
datanavigateurlfield="NewsURL"
datanavigateurlformatstring="http://{0}" />
In addition to making this change, you'll need to make sure that you are selecting the URL or something you can use to create the link to the news article. In the example above, I'm assuming the URL is something you can grab from your SQL source. If it is an ID, simply type out the rest of the url like this... "~/MyNewsPage.aspx?NewsID={0}"...
Use hyperlinkfield instead :
<asp:hyperlinkfield datatextfield="NewsHeadline"
datanavigateurlfields="NewsID"
datanavigateurlformatstring="~\newsdetails.aspx?Id={0}" />
You need to use a hyperlink field instead of a BoundField, like so:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display.">
<Columns>
<asp:HyperLinkField HeaderText="NewsHeadline" SortExpression="NewsHeadline" DataTextField="NewsHeadline" NavigateUrl="..." />
</Columns>
Something like this will work fantastic as a solution in Visual Studio 2010.
Create a GridView in the Designer tab of your webpage in VS.
Hover your mouse over the GridView and click the arrow that appears in the top right.
Go to "Choose Data Source" and select "new data source..."
Create the connection string to your database and choose the NewsHeadline table.
Write the query SELECT News_Id, NewsHeadline FROM NewsHeadline
Finish the setup. Now some code should be generated in the Source tab. This will also create an SqlDataSource which is now the DataSource of your GridView.
Go to where the code is for your GridView in the Source tab and replace with the following code.
Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField
DataNavigateUrlFields="News_Id"
DataNavigateUrlFormatString="~\newsdetails.aspx?News_Id={0}"
DataTextField="NewsHeadline"
HeaderText="News HeadLines"
SortExpression="NewsHeadline" />
</Columns>
</asp:GridView>
And you're all set. This will create a list of all the Headlines as hyperlinks with a dynamically generated unique link to the newsdetails.aspx page compliments of the query string we built using the PRIMARY KEY News_Id corresponding to each NewsHeadline entry in the NewsHeadline table.
Then when you load the newsdetails.aspx page you use: Request.QueryString["News_Id"] to get the News_Id value from the URL and use it to query the database for the details about the specific NewsHeadline that was clicked. You can then display the result of that query on the webpage.
The HyperLinkField will work great as others have pointed out. But, in case you want the entire row clickable, you can use a custom server control that implements a GridView suggested in the SO post "Making an entire row clickable in a gridview".
Check out the question I posted on how to implement a C# custom server control on implementing it.
Just another option.
I'd like to know if it is possible to set a field of a DetailsView BoundField (in edit mode) from javascript? I can't set an id for the boundfield, so obviously can't use document.getElementById() to get to it, but I was wondering if there's another way to do it?
You could try to create an EditItemTemplate, place a TextBox inside and give it an ID of your choice.
Like this:
<Fields>
<asp:TemplateField HeaderText="Column1">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
If there is stuff to be bound on the TextBox's Text property you could use Bind() method.
Good Luck.
I have a Gridview boundfield where i set ReadOnly to true because i don't want user to change its value. However on the objectdatasource control's update method that boundfield became null when i try to use it as parameter in update method. Is there a way to set that value during updating?
No, just add the field name you need to the DataKeyNames attribute of the GridView. Then the value will be sent to the Update command.
When you mark a field as read-only on the GridView it renders on the page as a span element, not an input. Therefore the value is not available on PostBack. If you can construct the update statement so that it doesn't expect this field, that would be the best way to deal with this. If the update statement is autogenerated and you can't get around having the value to update, then you can either read the value from the database before doing the update (so that you have it) or include a HiddenField bound to this column and use a literal that obtains the value via Eval instead of binding (if necessary). This will require using a template.
<asp:TemplateField>
<InsertItemTemplate>
<asp:TextBox runat="server" ID="itemTextBox" />
</InsertItemTemplate>
<EditItemTemplate>
<asp:HiddenField runat="server" ID="itemHF" Value='<% Bind("Item") %>' />
<asp:Label runat="server" ID="itemLabel" Text='<% Eval("Item") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="itemLabel" Text='<% Bind("Item") %>' />
</ItemTemplate>
</asp:TemplateField>
Another approach is to add a new query to your tableadapter. Create an update query that just uses the fields desired to be updated. When selecting the update method on the ODS pick the update query. The BoundFields that are not part of the update query can now be turned to readonly=true and it should work.
I had a similar problem and solved it in a slightly different way. But in my case the parameter I wanted to use in my Update method was my primary key and was available in a Query string. So in my DataSource definition I defined the UpdateParameters section to use instead of . Then I was able to remove the parameter completely from my table and it would revert to the Query string parameter.