How to create a link text in a table using c# - c#

I want to create a table format with two columns where each row will have a ProductTitle and its corresponding URL.
I am using the following code which gives the info in table format. I displays entire anchor tag in second column.
But i want only the Text to be displayed as link in second column. On click of which it should open the URL page.
DataTable dt = new DataTable();
dt.Columns.Add("ProductTitle");
dt.Columns.Add("Link");
DataRow dr = dt.NewRow();
dr["ProductTitle"] = "GOOGLE";
dr["Link"] = "<" + "a href=\"" + "http://www.google.com" + "\">Google" + "</a>";
dt.Rows.Add(dr);
Gridview1.DataSource = dt;
Gridview1.DataBind();
Could anyone suggest.

You could modify the .aspx file as follows:
...
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ProductTitle" HeaderText="Product Title" />
<asp:BoundField DataField="Link" HtmlEncode="false" HeaderText="Link" />
</Columns>
</asp:GridView>
...
So, you should disable the automatic column generation by setting AutoGenerateColumns="false" and format the Columns section of the GridView. Please note the key element here for the link rendering, which is the HtmlEncode="false" attribute. You can also set everything in the code behind file:
GridView1.AutoGenerateColumns = false;
var productTitleField=new BoundField();
productTitleField.DataField="ProductTitle";
productTitleField.HeaderText="Product Title";
var linkField=new BoundField();
linkField.DataField="Link";
linkField.HeaderText="Link";
linkField.HtmlEncode=false;
GridView1.Columns.Add(productTitleField);
GridView1.Columns.Add(linkField);

Try this
dr["Link"] = "<a href='http://www.google.com'>Google</a>";
I tried
Label1.Text = "<a href='http://www.google.com'>Google</a>";
It works.
Second try :
We cannot save any thing else other than .NET types like string,int .etc ,so try asp:HyperLink like this
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductTitle")%>' NavigateUrl='<%# Eval("Link") %>'></asp:HyperLink>
</ItemTemplate>
and
dr["ProductTitle"] = "Goole";
dr["Link"] = "http://www.google.com";

There is actually a specific column designed just for what you want to do, it's the HyperLinkField column.
<asp:HyperLinkField
HeaderText="Header"
DataTextField="LinkText"
DataNavigateUrlFields="LinkURL"
DataNavigateUrlFormatString="http://google.com/q={0}" />
You can then ensure that your data source has the appropriate columns for the link text and navigate url fields.
You can configure it if you have a fixed text or fixed url to use the Text or NavigateURL properties instead of the Data... counterparts, and you can use or not use format strings as needed.

Related

Double columns in GridView, building from code behind in C#

I'm trying to fill a GridView with a RadioButton and data from a CreditCardList. However, it's doubling the columns for each field... one full set of columns then another complete set (sans the RadioButton) I've checked creditCardList.items.Count and made sure it's just 1 (which it is). What am I doing wrong?
aspx:
<asp:GridView ID="gvCards" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Sel">
<ItemTemplate>
<asp:RadioButton ID="Sel" runat="server" GroupName="rad" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Customer ID" />
<asp:BoundField DataField="Card ID" HeaderText="Card ID" />
<asp:BoundField DataField="Card Number" HeaderText="Card Number" />
<asp:BoundField DataField="Expiration" HeaderText="Expiration" />
<asp:BoundField DataField="State" HeaderText="State" />
</Columns>
</asp:GridView>
Code behind:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Customer ID", typeof(string));
dt.Columns.Add("Card ID", typeof(string));
dt.Columns.Add("Card Number", typeof(string));
dt.Columns.Add("Expiration", typeof(string));
dt.Columns.Add("State", typeof(string));
for (var i = 0; i < creditCardList.items.Count; i++)
{
DataRow row1 = dt.NewRow();
row1["Name"] = creditCardList.items[i].first_name + " " + creditCardList.items[i].last_name;
row1["Customer ID"] = creditCardList.items[i].external_customer_id;
row1["Card ID"] = creditCardList.items[i].id;
row1["Card Number"] = creditCardList.items[i].number;
row1["Expiration"] = creditCardList.items[i].expire_month + "/" + creditCardList.items[i].expire_year;
row1["State"] = creditCardList.items[i].state;
dt.Rows.Add(row1);
}
gvCards.DataSource = dt;
gvCards.DataBind();
Output:
Sel Name Card ID Card Number Expiration State Name Customer ID Card ID Card Number Expiration State
Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok
set AutoGenerateColumns="false" .
<asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="false">
<Columns>
</Columns>
</asp:GridView>
Remarks
When the AutoGenerateColumns property is set to true, an AutoGeneratedField object is automatically created for each field in the data source. Each field is then displayed as a column in the GridView control in the order that the fields appear in the data source. This option provides a convenient way to display every field in the data source; however, you have limited control of how an automatically generated column field is displayed or behaves.
Instead of letting the GridView control automatically generate the column fields, you can manually define the column fields by setting the AutoGenerateColumns property to false and then creating a custom Columns collection. In addition to bound column fields, you can also display a button column field, a check box column field, a command field, a hyperlink column field, an image field, or a column field based on your own custom-defined template.

display specific Fields in gridView in asp.net

i want to display some fields from my database in GridView but my problem is, it show all the field i want in one new field
this is my code
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
and this is c# code
GridView1.DataSource = (from x in db.Products
select x.name + x.phoneNumber + x.proviance + x.description + x.city + x.Address).ToList();
GridView1.DataBind();
how to display some fields of a table (not all fields) into gridView in c# in asp.net
With Respect
So by default GridView generates columns for all fields/columns in the data set it was given. To select what you see you need to turn this off and explicitly declare desired columns:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="name of the column in the data set"
HeaderField="header to show on the UI"/>
... and so on for other columns ...
</Columns>
</asp:GridView>

Need to add a hyperlinkfield to a gridview containing data from another column

I have a gridview that gets data from an sqldatasource and as a results gets 3 columns from an SQL query: ID, description and price.
What I want to do is adding another column with an hyperlink in the format of page.aspx?id=x where x is the ID code from the first column. This for each row in the table.
I've been looking all morning for how to do this, all I got is that I have to manage the RowDataBound event and use an hyperlinkfield but couldn't find anything else that explained how they actually work together, even the msdn article is kind of vague on the subject or just doesn't have any relevant help for my specific case as I'm managing the gridview from the code-behind.
Also haven't been able to figure how to access strings from the other columns, since it's what I need to insert in the resulting hyperlink.
Here's what I got so far for the creation of the gridview:
private void FillGrid(string qid)
{
SqlDataSource1.ConnectionString = Connessione.connectionString;
SqlDataSource1.SelectCommand = "SELECT art_tessuto_articolo, art_tessuto_descrizione, lipre_prezzo FROM lipre INNER JOIN listini_tessuti ON lipre.lipre_codice = listini_tessuti.listini_codice INNER JOIN art_tessuti ON lipre.lipre_articolo = art_tessuti.art_tessuto_articolo WHERE lipre_codice = #qid AND lipre_prezzo <> 0";
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("qid", qid);
GridView1.AllowPaging = true;
GridView1.PageSize = 500;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
This should do the job.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlControl = new HyperLink();
hlControl.Text = e.Row.Cells[0].Text;
hlControl.NavigateUrl = "page.aspx?id=" + e.Row.Cells[0].Text;
e.Row.Cells[3].Controls.Add(hlControl);
}
}
Use HyperlinkField
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperlinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="page.aspx?ID={0}" />
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" Text="VisibleText" NavigateUrl='<%# Eval(columnname) %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

string.replace databound column in Gridview

Im currently pulling a string comment from a DB into a gridview to display to the user. Throughout the string i have placed <br/>s where i want linebreaks, but am wondering how to replace the <br/>s with "Environment.Newline"s. the column is simply a boundfield.
<Columns>
<asp:BoundField HeaderText="Comment" DataField="UAComment" />
</Columns>
and im populating the table with an adapter and Fill():
adapter = new SqlDataAdapter(queryString, connection);
connection.Open();
adapter.SelectCommand = command;
recordsFound = adapter.Fill(table);
results.Text = recordsFound + " records matching query";
connection.Close();
Thanks for any info.
ps: also tried already building the string/submitting the string to the database with newlines but cant seem to get it to pull out of the db with the proper formatting.
public void Group(String message)
{
log.Append(": Group :");
log.AppendFormat(message);
log.Append("<br/>");
}
public String GetLog()
{
log.Replace("<br/>", Environment.NewLine);
return log.ToString();
}
also substituted "Environment.Newline" with #"\n", "\n", #"\r", "\r"
The easiest solution would be use a template field instead of bound field and add bind a literal in the template field with current column value. Using this it will render all the stuff in html format and the line breaks come autometically.
Example :
<asp:TemplateField>
<HeaderTemplate>
Comment
</HeaderTemplate>
<ItemTemplate>
<asp:Literal runat="server" ID="Literal1" Text='<%# Eval("UAComment") %>' />
</ItemTemplate>
</asp:TemplateField>
Hope this will fix you problem

Unable to set column elements as hyperlink

I'm trying to set the first column elements as hyperlinks redirecting to another page..but somehow it doesn't seem to work no matter what I try.
reportTable.Rows[i].Cells[1].Text = report.reportId.ToString();
TableCell tCell = new TableCell();
tCell.Controls.Add(new LiteralControl(" report.reportId.ToString ()"));
// Create Hyperlink Web Server control and add to cell
System.Web.UI.WebControls.HyperLink h = new HyperLink();
h.Text = reportTable.Rows[i].Cells[1].Text = report.reportId.ToString();
h.NavigateUrl = "~/manage.aspx";
tCell.Controls.Add(h);
reportTable.Rows[i].Cells[2].Text = bench.mechId;
reportTable.Rows[i].Cells[3].Text = bench.elecId;
reportTable.Rows[i].Cells[4].Text = bench.name;
asp.net Grid and data controls are very good for data binding.
Also they provide Item templates that can be customized to include links, drop down lists, etc.
Do not populate your grid by manually creating all the controls. That totally defeats the purpose of using a grid.
e.g:
<asp:GridView ID="ReportsGridView"
DataSourceID="ReportsDataSource"
AllowPaging="true"
AutoGenerateColumns="false"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server"
ID="RedirectButton"
CommandName="Manage"
PostBackUrl="~/manage.aspx"
Text="Manage" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name"
HeaderText="Report Name"/>
</Columns>
</asp:GridView>

Categories