I am creating a webpage using C# and asp.net
I have a simple sqlite database.
I have a gridview where i am displaying just simple 2 Book categories.
The two categories are
Fiction
technical
I would like to assign a link to those categories so the user can be directed to a new page.
Here is a snapshot of the data being displayed in the gridview..
where i want to add a link to Fiction and technical to redirect to a new page.
This is my dataset and gridview.
DataSet dsgrid;
dsgrid = (DataSet)Cache["GridViewDataSet"];
if (dsgrid == null)
{
dsgrid = GetDataSet(); //call function
Cache["GridViewDataSet"] = dsgrid;
}
else
{
}
//bind our cache data to a datasource
GridView1.DataSource = dsgrid.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
this.lblError.Text = ex.Message;
}
}
private DataSet GetDataSet()
{
String connectionString = "Data Source=" + Server.MapPath(#"~\App_Data\bookDB.db");
String selectCommand = "Select * from Category";
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
//GridView1.DataSource = ds;
// GridView1.DataBind();
return ds;
}
Thank you
Here are a few options, which one you choose will depend on the amount of flexibility you need.
Built in button column:
<asp:GridView >
<Columns>
<asp:ButtonColumn DataField="some_field" Visible="false" ButtonType="linkButton" />
</Columns>
/<asp:GridView >
Column template: (This will give you the most flexibility.)
<asp:GridView>
<Columns>
<asp:TemplateField HeaderText="Its a link!">
<ItemTemplate>
<asp:LinkButton ID="SomeName" runat="server" Text=''>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Enjoy!
this is the markup code, you have to add a hyperlink to the gridview control inside the IntemTempalte collection and add a binding expression to the text property of the contained controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="128px">
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblCodigo" runat="server" Text='<%#Eval("columnNae")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="link" runat="server" Text='<%#Eval("columnNae") %>' NavigateUrl="http://nudierweb.somee.com"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to use HyperLinc control
<asp:HyperLink id="hyperlink1" NavigateUrl="http://www.yournavigateurl.com"
Text="Your Hyperlink text" runat="server"/>
Try like this
<asp:HyperLinkField DataTextField="Value of column you want to make as HYPERLINK" HeaderText="COLUMN NAME" runat="server" DataNavigateUrlFields="Value you want to pass to other page(fname)" DataNavigateUrlFormatString="~/demo.aspx(another page name)?fname**strong text**={0}"/>
eg:
<asp:HyperLinkField DataTextField="stid" HeaderText="stid" Target="_self" runat="server" DataNavigateUrlFields="fname" DataNavigateUrlFormatString="~/demo.aspx?fname={0}"/>
Related
This question already has an answer here:
How to add a Hyperlink to a dynamic gridview column
(1 answer)
Closed 7 years ago.
I created page with GridView, but I need to make links in 1 column, if I try to put <a> tag it doesn't work, it just shows plain html <a> tag.
I need at first row link to otherpage.aspx?id=1, second row otherpage.aspx?id=2 and so on.
Grid.aspx
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="4"
ForeColor="#333333" GridLines="None" PageSize="5" ViewStateMode="Enabled"
Width="100%" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<AlternatingRowStyle BackColor="White" />
<Columns>
</Columns>
</asp:GridView>
Grid.aspx.cs
DataTable data = new DataTable();
data.Columns.Add("New column");
// others columns
for (int i = 1;i < 10; i++)
{
data.Rows.Add();
data.Rows[i]["New column"] = "Link";
// other columns
}
GridView1.DataSource = data;
GridView1.DataBind();
Or is any better solution to create links in GridView (programmatically)?
You can use code like this:
foreach (GridViewRow gr in gv.Rows)
{
HyperLink hp = new HyperLink();
hp.Text = gr.Cells[0].Text;
hp.NavigateUrl = "~/Default.aspx?name=" + hp.Text;
gr.Cells[0].Controls.Add(hp);
}
For more samples you can see this link create links in dynamically created grid view
Instead of adding a new column in the DataTable, you can add a TemplateField to your GridView and put a HyperLink control in it. The Hyperlink control renders as an a tag in HTML.
Using the TemplateField has the advantage that you do not have to create controls dynamically (which sometimes is not the most stable approach). For more details on the TemplateField see this link.
ASPX
For your requirements, you can set the properties of the HyperLink control directly in the ASPX:
<asp:GridView ID="gdv" runat="server" AutoGenerateColumns="false" OnRowDataBound="gdv_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="lnk" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Text") %>'
NavigateUrl='<%# "otherpage.aspx?id=" + DataBinder.Eval(Container.DataItem, "Id").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ASPX and Code Behind for a more complex scenario
For a more complex scenario, you can set the properties in Code Behind:
<asp:GridView ID="gdv" runat="server" AutoGenerateColumns="false" OnRowDataBound="gdv_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="lnk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var lnk = (HyperLink)e.Row.FindControl("lnk");
lnk.NavigateUrl = "otherpage.aspx?id=" + ((DataRowView)e.Row.DataItem)["Id"].ToString();
lnk.Text = ((DataRowView)e.Row.DataItem)["Text"].ToString();
}
}
In the RowDataBound event, the HyperLink control in the TemplateField is identified and the Text and NavigateUrl properties are set.
I need to create a typ of board to show who's who in form of a datagrid. in each cell I have to show picture, name and department. any suggestion on how to do this ? something where I can create a template and inserted in datagridview control. thanks
Add GridView control on page, bind with DataSet, display result.
Use two column in GridView,
BoundColumn for ID column
TemplateColumn for Picture Column, Name column, Department column
Also add OnRowDataBound event.
Write a sql query or stored procedure which return Desired reult from Database and create DataSet using it. Below is the sample code (not tested)
IN .aspx page
<asp:GridView runat="server" ID="gdImage" AutoGenerateColumns="false"
OnRowDataBound="gdImage_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:TemplateField HeaderText="Information">
<ItemTemplate>
<asp:Image ID="ctrlImage" Width="15px" runat="server" alt='<%#
DataBinder.Eval(Container.DataItem, "Image") %>'></asp:Image>
<asp:Label ID="lblName" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'></asp:Label>
<asp:Label ID="lblDept" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Dept") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
SqlCommand cmd;
con = new
SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString);
con.Open();
da = new SqlDataAdapter("select Id,Name,Dept,Image from tablename",con);
ds = new DataSet();
da.Fill(ds);
gdImage.DataSource = ds;
gdImage.DataBind();
}
I am trying to make gridview last column fields Button.
Trying but could not do this.
It is possible while adding column in gridview using sql data source. But to do this using this binding method.
Here is my code-
private void BindUserRoles()
{
gvUserRoles.DataSource = UserRoles.GetAllRoles();
gvUserRoles.DataBind();
}
public List<UserRoles> GetAllRoles()
{
try
{
List<UserRoles> userRoles = new List<UserRoles>();
using (IDataAccess dataAccess = Mspl.MobileTracking.DataAccess.DataAccess.GetDataAccess("TrackingConnectionString"))
{
var dataReader = dataAccess.RetrieveData("GetAllRoles", null);
while (dataReader.Read())
{
UserRoles roles = new UserRoles();
roles.RoleId = dataReader["RoleId"].ToString();
roles.RoleName = dataReader["RoleName"].ToString();
userRoles.Add(roles);
}
}
return userRoles;
}
catch (Exception ex)
{
return null;
}
}
<asp:GridView ID="gvUserRoles" runat="server" EnableModelValidation="True"
</asp:GridView>
Set AutoGeneratedColumn=false and add templatefields like shown below.
Change your grid code like this-
<Columns>
<asp:BoundField DataField="RoleId" HeaderText="RoleId" ItemStyle-CssClass="HideColumn" HeaderStyle-HorizontalAlign="Left"/>
<asp:TemplateField HeaderText="Role Name" HeaderStyle-CssClass="normalText">
<ItemTemplate>
<asp:Label ID="lblRoleName" CssClass="normalText" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEditRole" runat="server" Text="Edit" OnClick="EditRoles_Click"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Just replace your current "last" column with a ButtonField, for example:
<asp:ButtonField ButtonType="button" CommandName="MoreDetail"
HeaderText="More Details" Text="More Details" />
Please try below link
add boundField to gridview in codebehind file C#
Code project link
http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view
i made a GridView in Asp with 1 BoundField,1 Button Field,1 command field ,1 template field with Button inside and here is code
<asp:GridView runat="server" ID="rdGrid" ForeColor="#333333" BorderWidth="1px">
<Columns>
<asp:BoundField HeaderText="Description" DataField="Description" />
<asp:ButtonField Text="View Summary" CommandName="Summary" ControlStyle-CssClass="btn btn-primary btn-small" ControlStyle-ForeColor="White" />
<asp:CommandField EditText="Edit" ShowEditButton="true" ControlStyle-CssClass="btn btn-primary btn-small" ControlStyle-ForeColor="White"></asp:CommandField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="deleteButton" CssClass="btn btn-danger btn-small" runat="server" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this Player?');" />
<%--<asp:HiddenField id="rdId" Value='<%# Eval("roundId") %>' runat="server" />--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this is output i am getting .. something very weird
and hidden field Eval Says it doesn't exist in current context giving out an Exception .. that's why i commented hidden field..
Code used to Bind Grid
string cs = ConfigurationManager.AppSettings["ConnectionString"];
MySqlConnection register = new MySqlConnection(cs);
register.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM rounds;", register);
MySqlDataAdapter dataadapter = new MySqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
dataadapter.Fill(ds, "rounds");
register.Close();
DataTable dt = new DataTable();
dt = ds.Tables["rounds"];
DataTable dt1 = new DataTable();
dt1.Columns.Add("Description");
dt1.Columns.Add("roundId");
foreach (DataRow dr in dt.Rows)
{
dt1.NewRow();
string des = dr["Description"].ToString();
string rid=dr["roundId"].ToString();
dt1.ImportRow(dr);
string[] arr1D = { des,rid };
}
rdGrid.DataSource = dt1;
rdGrid.DataBind();
rdGrid.RowCommand += rdGrid_RowCommand;
As per your Image with grid view you have two columns as description, it seems you have to put
AutoGenerateColumns as false in your grid view as below
<asp:GridView runat="server" AutoGenerateColumns="false" ID="rdGrid" ForeColor="#333333" BorderWidth="1px">
than you will not get additional description column in UI.
And also if you binding more columns, they should also appear as auto generated columns. but now you have only the description column.
You may need to change the select statement to fetch all the columns you need
select roundId, Description, .... from YourTable
For the round ID I think you use the DataKeyNames attribute of gridview.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames%28v=vs.110%29.aspx
I have DataTable like this:
I need to combine "Headline 1-2-3" Columns to one, like this:
Unfortunately GridView.TableCell can not be applied here.
How can I combine Columns, using C# ASP.NET?
You could use an asp.net repeater instead of a gridview.
the repeaters DataSource will be your source for the tables and don't forget to DataDind() the repeater.
then in the itemdatabound (rpeaterId.ItemDataBound += {by pressing += visual studio will suggest to create the method for you by pressing the Tab button twice :) }) function of the repeater you can set a if statement for the headers
You'll need to write more code if you need more help.
I hope this will give you an instight and help you solve your problem.
Cheers!
You can use something like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="address" HeaderText="address" visible="false"/>
<asp:BoundField DataField="city" HeaderText="city" visible="false"/>
<asp:BoundField DataField="region" HeaderText="region" visible="false"/>
<asp:BoundField DataField="postalcode" HeaderText="postalcode" visible="false"/>
<asp:TemplateField HeaderText="Full Address">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label">
<%# Eval("address") + ", " + Eval("city") + ", " + Eval("region") + ", " + Eval("postalcode")%>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then all you need to do is return the rquired "bound" data, and let the template do the rest:
private void LoadEmployeeAddress()
{
string con = ConfigurationManager.AppSettings["NorthwindDatabase"];
string sql = "select address, city, region, postalcode from employees;";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}