Binding GridView to array of strings. Problem with HyperLinkField - asp.net

I know that you can use exclamation sign to bind array of simple types (like string) to GridView like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Array Field" DataField="!" />
</Columns>
</asp:GridView>
But this doesn't seem to be the case with DataNavigateUrlFields
<asp:HyperLinkField DataNavigateUrlFields="!" DataNavigateUrlFormatString="RoleInformation.aspx?role={0}" Text="Manage users" />
and I get following error:
A field or property with the name '!' was not found on the selected data source.

Most people probably haven't even know to use the ! field I suspect. When I read your question it actually made me remember that feature which I had read about but never actually used. With that in mind, I don't think there is a way with that type of field because it was probably forgotten in the HyperLinkField implementation (just a guess). You could just do a quick conversion to named property and then you don't have any issues:
Example:
<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Array Field" DataField="data" />
<asp:HyperLinkField DataNavigateUrlFields="data" DataNavigateUrlFormatString="RoleInformation.aspx?role={0}" Text="Manage users" />
</Columns>
</asp:GridView>
Notice the field named data. Then to bind your array just do:
string[] testArray = { "1", "2", "3" };
grdTest.DataSource = testArray.Select(a => new { data = a });
grdTest.DataBind();
It doesn't replace the ! directly but it is a simple solution to get around binding to simple arrays that will always work even when the ! isn't implemented which it probably needs to be for each field type.

Related

Gridview Hyperlinkfield using DataNavigateUrlFormatString with Ampersand

So I have gridview pulling fields from a table and my hyperlinkfield is used to go to a specific page for that row to get more detailed data. Everything seems to work great except when the field used in the hyperlinkfield has an ampersand. I assume it is reading the ampersand as something else and so it doesn't bring up the proper info because the ampersand is in the name in the database.
Hyperlinkfieldcode:
<asp:HyperLinkField HeaderText="Name" Text="{0}" DataNavigateUrlFields="Name" DataNavigateUrlFormatString="item.aspx?name={0}" DataTextField="Name" />
Example:
A clicking on the name "test item" would take you to mysite.com/item.aspx?name=test%20item and this works.
However, clicking on "test & test item" it takes you to mysite.com/item.aspx?name=test%20item%20&%20item which does not work. It just pulls up a page with blank info.
What can I do to fix this?
Update:
I converted the hyperlinkfield to a hyperlink inside a template field, but the url is now coming out weird.the url now comes out like mysite.com/item.aspx?name=System.Int32%5b%5d
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%#Eval("Name") %>' DataNavigateUrlFields="Name" NavigateUrl='<%# "name.aspx?name=" + HttpUtility.UrlEncode({0}.ToString())%>' DataTextField="Name" />
</ItemTemplate>
</asp:TemplateField>
My original answer was incomplete (due to not being able to see the entire code). This answer will contain the missing elements.
The main object is to UrlEncode the data field Name, so that it can be used as (part of) a url link .
1 - First we must ensure that the field "Name", is listed as DataKeyNames for the GridView as follows:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name" ...
2 - Secondly (if using a navigateURL) create a TemplateField i.e. (asp:TemplateField ) and use Eval() method to access the DataField in conjunction with UrlEncode() .
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="NameLink" runat="server" Text='<%# Eval("Name") %>' NavigateUrl='<%# "name.aspx?name=" + HttpUtility.UrlEncode(Eval("Name").ToString())%>' ></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Option 2 Alternatively you can use a HyperLinkField and DataNavigateURL but you should still designate Name as a DataKeyNames .
Hope this works with no problems. Let me know if any clarification is needed.
Happy coding and Cheers,

How to bind part of form values to model in asp.net webform

I inherited an asp.net webform application. Now when I try to add new feature to it. I hit the following stop:
I created a form to get data from end user, and the data goes into two tables in the database.
I used Entity Framework to deal with communication with database.
My question is, because the form data need to go into two models(two tables), can I bind one model to part of the form data?
Or there is no way to do that, I have to go through each and every form data and assign them to the model properties?
for example
data model would be
class ModelA{
public int ModelAID {get;set;}
public string ModelAName {get;set;}
}
class ModelB{
public int ModelBID {get;set;}
public string ModelBName{get;set;}
}
front end page would be
<form>
<input name="Aid"/>
<input name="AName"/>
<input name="Bid"/>
<input name="BName"/>
</form>
code behide would be
What kind of version are you using?
I'm developing in web forms 4.5, and I have suffered with the similar problem.
The short answer is.. kinda difficult but you can do it with some restrictions.
For data binding, I'm not sure what you mean..
if you want to just bring the data, or you want to update and delete the data as well.
For me, I am using gridview everywhere to show the data and also to update, delete it, and in my experience, updating and delete is possible for one table.
But you could show other table's data by showing it in ItemTemplate.
Here is a short example of what i did :
<asp:GridView runat="server" ItemType="model"
ID="someGrid" SelectMethod="someGrid_GetData" CellPadding ="10"
autoGenerateColumns="false" deleteMethod="someGrid_DeleteItem"
updateMethod="someGrid_UpdateItem" DataKeyNames="id"
AutoGenerateDeleteButton="true" AutoGenerateEditButton="true">
<Columns>
<asp:DynamicField DataField="col1" />
<asp:BoundField DataField="col2" HeaderText="col2" />
<asp:TemplateField HeaderText="details">
<ItemTemplate>
<asp:HyperLink ID="detailLink" runat="server" Text="details" NavigateUrl='<%# "~/someDetails?some=" + Eval("someDetails") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="vendor">
<ItemTemplate>
<asp:Label ID="vendorLbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
as you can see, you could update, delete the data from model table, but you can also put data inside vendor as a label from the code behind.
I've spent many time figuring about this.
And hope this helps!

gridview column boundfield error

Inside GridView, then inside columns I have a bound field
<asp:BoundField DataField="Company Name" HeaderText="Company Name" SortExpression="Name" />
This displays a list of columns of the companys name (which is fine) however the headerText, is a clickable link that throws an error...how can i get the headertext just to display as a normal plan unclickable label
ta
You can use AllowSorting="False" to the gridview.
<asp:GridView AllowSorting="False">
<asp:BoundField DataField="Company Name" HeaderText="Company Name"/>
</asp:GridView>
Probably because you marked the bound field to be sortable and you didn't implement the sort on the server side... probably. Remove the SortExpression and see what's happening. You should post more info starting with the exception you have.
just remove the SortExpression

Eval() in ASP. How to pass values on redirect

<asp:GridView ID="GridView1" runat="server" CssClass="style29">
<Columns>
<asp:TemplateField HeaderText="Send Message to Group">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl='SendMessage.aspx?GroupName=<%# Eval("GroupName") %>' Text='Send Message'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am redirecting the to SendMessage.ASPX page which has a text box, I have to pass the group name to that text box. Please help me guys I am new to programming. It gets redirected but how to pass that value to this text box below in SendMessage.aspx page.
Sorry I may have misunderstood your question, however the common pattern involves the query string
You can access the query string values as
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["GroupID"]) == false) {
String groupId = HttpContext.Current.Request.QueryString["GroupID"];
}
you would then be able to set this value to the textbox.Text property in your page load event, which will apply the value from the query string to the textbox.
Generally, you want to check for null or empty strings before attempting to access the query string.
Also, always remember that this kind of action is often a target for malicious users to do malicous things with your website, so you must check inputs to ensure 'bad' inputs are ignored.

Data binding boundfields in web form

I have the following DetailsView, with several BoundFields, and SQlDataSource that populates the fields:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="TICKET_ID"
DataSourceID="SqlDataSource1" HeaderText="Completed IT ticket information"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center">
<Fields>
<asp:BoundField DataField="TICKET_ID" SortExpression="TICKET_ID" Visible="False" />
<asp:BoundField DataField="SUBMITTED_BY" SortExpression="SUBMITTED_BY" Visible="False" />
<asp:BoundField DataField="TICKET_TITLE" HeaderText="Ticket Description" SortExpression="TICKET_TITLE" />
<asp:BoundField DataField="SUBMITTED_BY" HeaderText="Submitted By" SortExpression="SUBMITTED_BY" />
<asp:BoundField DataField="SOLUTION_NOTES" HeaderText="Solution Notes" SortExpression="SOLUTION_NOTES" />
<asp:BoundField DataField="EMAIL_HISTORY" HeaderText="Email History" SortExpression="EMAIL_HISTORY" />
<asp:BoundField DataField="COMPLETED_BY" HeaderText="Completed By" SortExpression="COMPLETED_BY" />
<asp:BoundField DataField="COMPLETE_DATE" HeaderText="Completed Date" ReadOnly="True" SortExpression="COMPLETE_DATE" />
</Fields>
</asp:DetailsView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TTPRODConnectionString %>"
SelectCommand="SELECT USR_ITFAC.TS_ID AS TICKET_ID, USR_ITFAC.TS_EC1_SUBMITTER AS SUBMITTED_BY, USR_ITFAC.TS_TITLE AS TICKET_TITLE, USR_ITFAC.TS_SOLUTION_NOTES AS SOLUTION_NOTES, USR_ITFAC.TS_EMAIL_HISTORY AS EMAIL_HISTORY, TS_USERS.TS_NAME AS COMPLETED_BY, DATEADD(HOUR,-8,USR_ITFAC.TS_CLOSEDATE) AS COMPLETE_DATE FROM USR_ITFAC INNER JOIN TS_USERS ON USR_ITFAC.TS_COMPLETED_BY = TS_USERS.TS_ID WHERE (USR_ITFAC.TS_ISSUEID = '00033')">
<SelectParameters>
<asp:QueryStringParameter Name="ts_id" QueryStringField="id" />
</SelectParameters>
</asp:SqlDataSource>
I hard-coded a value at the end of the query '00033', which is the ID of a record I know is in the database. I tested the query and it returns a value as expected, what I'm trying to do is fetch the values of the BoundField in the code-behind after a user has pressed a button.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
''Use a Dictionary to store answers to questions that were marked poor or fair
Dim answers As New Dictionary(Of String, String)
''For Each test
For Each dv_row As DetailsViewRow In DetailsView1.Rows
''Print rows data to console
Next
Catch ex As Exception
lblWarn.Text = "<br /><b>Please answer all the questions on this survey</b><br />"
'Response.Write(ex)
End Try
End Sub
Above I'm doing a test to fetch the values and print them onscreen, the problem is that the row count is 0, I'm not sure why that is. I expected the row count to be 8, when debugging I notice that the field count is 8, but I'm not sure how to get the values from the fields. I thought the way to get row data was something like:
Dim rowText As String = DetailsView1.Rows(0).Cells(1).Text
But when I try that I get a Null exception. Any insight is appreciated.
I misread the code. FindControl() is effective when using templates.
Try instead to use the FindControl(controlID) method on your details view to find your data-bound control. The method returns an object of type Control, so you'll probably have to type cast the result to get any real use out of it.
Was able to get it up and running. Turns out the BoundFields were not getting populated because the parameter in the QueryStringField, namely "id", was not being specified in the request URL. To resolve this I first tried to rewrite the URL path on Page_Load, that didn't work, so I just created a separate page with a hyperlink to the page I'm working on with a variable appended to the end of the URL which provides the QueryString for the SQLDataSource to reference. More on the QueryString property here.

Resources