Gridview Hyperlink column want display xml nodes as a link - c#

I have the following XML file:
<Employees>
<Employee>
<FirstName><a href='profile1.html'>Jon</a></FirstName>
<Age>22</Age>
</Employee>
</Employees>
what am attempting to do is have the FirstName to display as a hyperlink that directs the user to a profile page (web page).
The results from the XML file are displayed via a gridview after the user enters the first name into a text field and clicks the search button. However, the first name (search result) is currently being displayed as plain text.
The following is the code behind the search button:
XDocument document = XDocument.Load(#"C:\Users\Sammer\source\repos\MisaImports\MisaImports\data\Employee.xml");
var query = from r in document.Descendants("Employee")
where ((string)r.Element("FirstName").Value).Contains(txtSearch.Text) || ((string)r.Element("FirstName").Value).ToLower().Contains(txtSearch.Text)
select new
{
FirstName = r.Element("FirstName").Value,
//Age = r.Element("Age").Value
};
GridView1.DataSource = query;
GridView1.DataBind();
...the following depicts how I set up the gridview:
<asp:GridView ID="GridView1" runat="server"
BorderWidth="1px"
CellPadding="2"
EnableModelValidation="True"
ForeColor="white"
GridLines="None"
AutoGenerateColumns="False"
EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Keyword" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="link" runat="server" Text='<%# Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My question is, how do I get the first name to diplay as a hyperlink? Thanks in adavnce for any help rendered.

You can fetch the Url like this:-
select new
{
FirstName = r.Element("FirstName").Value,
Profile = x.Element("FirstName")?.Element("a")?.Attribute("href")?.Value ?? ""
};
Finally bind the NavigateUrl property like this:-
<asp:HyperLink ID="link" runat="server" Text='<%# Eval("FirstName") %>'
NavigateUrl='<%# Eval("profile") %>' />

Related

data Grid Data bound field header text change in c#

I have a datagrid that has a BoundColumn there I am trying to change the header text on page load I so fa. I have tried this.
<asp:datagrid id="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="True" BorderColor="AliceBlue" OnItemDataBound="dgTranscript_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="" ItemStyle-VerticalAlign="Top"></asp:BoundColumn>
</Columns>
</asp:datagrid>
C#
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = lblAverage.Text
I want to set the text to be the text that's inside that label but its not letting me if i say without the label it works
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = "Some Text";
Binding Data
DataSet ds;
DataRow drClient = null;
dgdata.Columns[1].HeaderText = lblAverage.Text; // Here before the Daatabind I set the text to be that label
DataConn.WebExecute(out ds);
DataConn.Bind(dgTranscript, ds);// This binds the data to the datagrid
It shows that text as the header but when I try punting in any string or a label text it denies the whole header disappears
Thanks in advance. Best Regards
If the value of lblAverage is set after calling DataBind on the datagrid then the header will remain empty.
This works
lblAverage.Text = "Some Text";
dgdata.Columns[0].HeaderText = lblAverage.Text;
dgdata.DataSource = mySource;
dgdata.DataBind();
While this will not
lblAverage.Text = "Some Text";
dgdata.DataSource = mySource;
dgdata.DataBind();
dgdata.Columns[0].HeaderText = lblAverage.Text;
You can try this.
<asp:Label ID="lblAverage" runat="server" Text="Header Value"></asp:Label>
<asp:DataGrid ID="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="true" ShowHeader="true" BorderColor="AliceBlue">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:Label ID="lblheader" runat="server" Text='<%# lblAverage.Text %>'></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblvalue" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

To add new row in gridview using javascript

In the below code i have gridview which has textbox and dropdownlist i want to add rows using javascript.My aim is to avoid postback on adding rows.
Markup code:
<asp:GridView runat="server" ID="gvProduct" AutoGenerateColumns="false"
Width="100%" CellPadding="4" ForeColor="#333333" ShowFooter="true"
PageSize-Mode="NumericPages" PagerStyle-Visible="true" AllowPaging="false" AllowSorting="true"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowDataBound="gvProduct_RowDataBound" OnRowCommand="gvProduct_RowCommand" OnRowDeleting="gvProduct_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Product Name" ItemStyle-Width="350px">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" AutoPostBack="false" Style="width: 100%; height:23px" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current Stock" ItemStyle-Width="80px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCurrentStock" runat="server" onkeypress="return isNumberKey(event, false);" Height="20px" style="width:80px" Enabled="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="80px">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" onkeypress="return isNumberKey(event, false);" runat="server" Height="20px" Width="150px" onblur="js_function(this);" > </asp:TextBox>
<asp:Label ID="lblunittype" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button2" OnClientClick="AddRow(); return false;" runat="server" Text="Button" />
Javascript code:
function AddRow() {
var table = document.getElementById('<%=gvProduct.ClientID %>');
var newRow = table.insertRow();
var i = 0;
for (i = 0; i < table.rows[0].cells.length; i++) {
var newCell = newRow.insertCell();
newCell.innerHTML = 'New Row';
}
}
Gridview in asp = Table in HTML
new row in Gridview in asp = new row in Table in HTML
Sample JavaScript code:
function AddRow() {
let tableRef = document.getElementById('MainContent_gvItems');
let newRow = tableRef.insertRow(-1);//inserts at last row
let Cell0 = newRow.insertCell(0);
let Text0 = document.createTextNode('mydata');
Cell0.appendChild(Text0);
}
Btw, GridView must be visible even it's empty.
If you just want to add rows to the table for presentation, then #Mostafa Shehata answer should work fine.
However adding rows in JavaScript does not attached it to the GridView datasource. Therefore you'll experience issues with processing the data in the backend (such as saving to database).
Two possible solutions:
Replace GridView with a html table. The data can be populated & updated using a JavaScript calls to a restful API.
Pre-populate the GridView datasource with empty rows.
Data-bind x amount of empty fields (for example 10 empty fields).
In the GridView markup hide all the rows using css.
Run JavaScript to show rows that are not empty.
The “add row” button can just show the first empty row.
Add some sort of notification, if all empty fields have been used. (for example: "please save your data, before continuing").
In code behind, remove all empty fields before consuming it.

Display DataGrid Column as Hyperlink Column depending on column value

I have the below DataGrid which works with no problem
<asp:DataGrid ID="fileBrowserGrid" runat="server" Width="100%" PageSize="14" AllowPaging="True"
CellPadding="1" GridLines="None" BorderColor="#636E92" BorderWidth="0px" AutoGenerateColumns="False"
OnPageIndexChanged="fileBrowserGrid_PageIndexChanged">
<AlternatingItemStyle CssClass="mainbodytextalt"></AlternatingItemStyle>
<ItemStyle CssClass="metadatabodytext"></ItemStyle>
<HeaderStyle CssClass="metadatabodytitle"></HeaderStyle>
<FooterStyle CssClass="Blue"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LoadedFileID" HeaderText="Loaded File Id" Visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierCode" HeaderText="Data Supplier Code"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierName" HeaderText="Data Supplier Name"></asp:BoundColumn>
<asp:BoundColumn DataField="Filename" HeaderText="File Name"></asp:BoundColumn>
<asp:BoundColumn DataField="DateLoaded" HeaderText="Date Loaded"></asp:BoundColumn>
<asp:BoundColumn DataField="LoadStatus" HeaderText="Status"></asp:BoundColumn>
</Columns>
<PagerStyle CssClass="Gray"></PagerStyle>
</asp:DataGrid>
code behind:
DataSet dataSet = results.DataSet;
this.fileBrowserGrid.DataSource = dataSet;
this.fileBrowserGrid.DataBind();
I want to change the Status column so that will display a hyperlink to errormessage.aspx with id as querystring value if the value is 'Failed' but stay as normal text value if its anything else.
Ideally I don't want to make changes to my stored procedures
I've been looking at RowDataBind but haven't been able to get that working.
Any ideas? Thank you!
I have a solution with only the aspx and not touch the cs backend
You can predict the render of template Column. Try this
I suppose that the code status that indicate failed is "failed"
<asp:TemplateColumn>
<HeaderTemplate>
<b>Status </b>
</HeaderTemplate>
<ItemTemplate>
<asp:PlaceHolder ID="Ok" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?false:true) %>'><%----%>
<asp:Label ID="Label1" Text='<%# Eval("LoadStatus") %>' runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder ID="Ko" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?true:false) %>'><%----%>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("DataLoaderErrorMessage.aspx?id={0}",Eval("LoadedFileID"))%>'><%# Eval("LoadStatus") %></asp:HyperLink>
</asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateColumn>
1) Set the AutoGenerateColumns property of the datagrid to false.
2) Create a template column instead of a bound column for the status.
3) Set the 'DataField' property for every column (Except the template column) so they know which value to display from the sql datasource.
4) Edit the template column and add a html div in there with the id divStatus
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<div id="divStatus" runat="server">
</div>
</ItemTemplate>
</asp:TemplateField>
Iterate through all the rows after setting the datasource of the gridview and do something like the following.
for(int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
HtmlGenericControl divStatus = (HtmlGenericControl)fileBrowserGrid.Rows[i].FindControl("divStatus");
if(dataSet.Tables[0].Rows[i]["LoadStatus"].ToString() != "Failed")
divStatus.InnerHtml = dataSet.Tables[0].Rows[i]["LoadStatus"].ToString();
else
divStatus.InnerHtml = "<a href='pageURL.aspx?ID=" + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "'> Failed : " + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "</a>";
}

How to display image in gridview from server floder?

I get error following code
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" runat="server" ImageUrl="~/Attachment/<%#Eval("Image") %>" />
</ItemTemplate>
</asp:TemplateField>
error
Parser Error Message: The server tag is not well formed.
First Try this:
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" runat="server" ImageUrl="<%# Page.ResolveClientUrl(String.Format("~/Attachment/{0}",Eval("Image"))) %>" />
</ItemTemplate>
</asp:TemplateField>
There is another option to do that in the server not in the client. its is useful if you need to set the image url in run time.
<asp:GridView runat="server" ID="gvActivities" AllowSorting="true" AllowPaging="true"
PageSize="25" AutoGenerateColumns="false" Width="100%" OnSorting="gvActivities_Sorting"
OnRowDataBound="gvActivities_RowDataBound">
<Columns>
<asp:TemplateField HeaderText='Image' HeaderStyle-Width="4%"
SortExpression="ActivityType">
<ItemTemplate>
<asp:Image ID="ImageType" runat="server" AlternateText='<%# Eval("Type") %>' />
</ItemTemplate>
</asp:TemplateField>
Has you can see, i am using the OnRowDataBound to set the image url.
I am not setting the ImageURL in the client.
I am checking if the Row type is a Data Row.
Then i am creating an image and putting the image from the grin into it. see that i am using the FindControl method. the "ImageType" is the id of the image in the grid.
then i am setting the imageURL Property
protected void gvActivities_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.Cells[0].FindControl("ImageType");
img.ImageUrl = Page.ResolveClientUrl("Image URL path);
img.AlternateText = "Text";
img.ToolTip = "Tooltip";
}
}

Conditional Logic for Gridview ItemTemplate (using mark up only)

I have a gridview as shown below. When the EmpType is contract the EmpID must be masked as "XXX"; for regular employees, actual EmpID should be shown. Also, when it is masked, I need to add a button control in the EmpID column.
I need to do it using mark-up; not using code behind. How can we write the conditional logic for Gridview's ItemTemplate for this logic?
Note: .Net 4.0
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="AssociateID" DataField="AssociateID" />
<asp:TemplateField HeaderText="EmpID">
<ItemTemplate>
<%# Eval("EmpID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="EmpType" DataField="EmpType" />
</Columns>
</asp:GridView>
CODE BEHIND
List<Associate> associatesList = new List<Associate>();
associatesList.Add(new Associate { AssociateID = 1, EmpID = 101, EmpType = "Contract" });
associatesList.Add(new Associate { AssociateID = 2, EmpID = 102, EmpType = "Regular" });
Gridview1.DataSource = associatesList;
Gridview1.DataBind();
Try this
<%# Eval("EmpType") == "Contract" ? "XXX" : Convert.ToString(Eval("EmpID"))%>
Instead of
<%# Eval("EmpID")%>
Following works
<asp:TemplateField HeaderText="EmpID">
<ItemTemplate>
<%# Convert.ToString(Eval("EmpType")) == "Contract" ? "XXX" : Convert.ToString(Eval("EmpID"))%>
<asp:Button ID="Button1" runat="server" Text="Button"
Visible='<%# Eval("EmpType") == "Contract" ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
Related:
Row number can be obtained by following Get GridView Selected Row Values using Page Previous Page
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"

Categories