Bind Literal control inside Gridview from codebehind. - c#

I have a gridview which contains template fields in which every template field contains a litreal control, and I want to bind that grid view with my DataSet, please look into the code to find more.
Code to create DataSet-
DataTable Record = new DataTable();
Record.Columns.Add("zerker");
DataRow dr = Record.NewRow();
dr["zerker"] = "SomeText";
Record.Rows.Add(dr);
gvCustomres.DataSource = Record;
gvCustomres.DataBind();
Code to create GridView-
<asp:GridView ID="gvCustomres" runat="server" PageSize="4" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Zerker">
<ItemTemplate>
<asp:Literal ID="zerkername" runat="server"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
Please help me to find correct way to do this.
Thanks,

Your code above is all right if you just want to bind Column "zerker" to your gridiview.
All you are missing is the Text Property for your Literal control.
<asp:Literal ID="zerkername" runat="server" Text='<%# Eval("zerker") %>'>
</asp:Literal>

Related

Adding hyperlink in gridview

I have a gridview which displays all a database table with columns TaskId, Title, Reward, Time Allotted, Poster Name. Although all my SqlConnection code is present on another webform which is used to insert data in to database table.
Here is my code on InsertTask.aspx.cs page:
protected void btnPost_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTasks", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", txtTitle.Text);
cmd.Parameters.AddWithValue("#Body", txtBody.Text);
cmd.Parameters.AddWithValue("#Reward", txtRewards.Text);
cmd.Parameters.AddWithValue("#TimeAllotted", txtTime.Text);
cmd.Parameters.AddWithValue("#PosterName", txtPoster.Text);
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Task Posted Successfully.";
}
}
This inserts task in to database table successfully. So on a new webform which is default.aspx, I have a gridview which is connected to that database table and shows a list of tasks in the table.
Again, I have not written any code on default.aspx.cs.
What I need to do is make Title as a hyperlink in the gridview which I can click and get on a different page which is in accordance to the rows. Can that be done? Or should I use a button on all rows to get to other pages accordingly. How can that be done?
I have no experience with gridview.
<telerik:GridTemplateColumn HeaderText="Action">
<ItemTemplate>
<a id="A1" runat="server" href='<%# #"~\Demolink.aspx"+( Eval("Record_ID").ToString()) %>'>
<%#Eval("Title ") %> </a>
</ItemTemplate>
</telerik:GridTemplateColumn>
According to your requirement get all data to a dataset or datatable and bind it to gridview. And in default.aspx markup we can convert gridview columns to hyperlink fields in different manners by using <asp:TemplateField><ItemTemplate></ItemTemplate></asp:TemplateField> in <Columns> tag
Here I added two controls one is html hyperlink and other is asp:hyperlink
<asp:GridView runat="server" ID="gvrecords" AutoGenerateColumns="false" DataKeyNames="Title">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Title") %>' NavigateUrl='<%# Bind("Title", "~/../urpath/{0}") %>' runat="server"/>
<a href ='<%#"page.aspx?TitleID="+DataBinder.Eval(Container.DataItem,"TitleId") %>'> <%#Eval("Title") %> </a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Yes of course you can use hyperlink for title. To provide hyper link you can use TemplateField as mentioned in below code sample :
<asp:GridView runat="server" ID="gridTask" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Eval("Title") %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Body" HeaderText="Body" />
<asp:BoundField DataField="Reward" HeaderText="Reward" />
</Columns>
</asp:GridView>
Note: Here I have used stackoverflow site url. instead you can use the url of your page.
<asp:TemplateField>
<ItemTemplate>
<%#Eval("Title") %>
</ItemTemplate>
</asp:TemplateField>
This should work!

How to select a cell in datagrid onClick in ASP.net C#

I am importing a column in datatable to my grid. Now I want navigate to a new page on selecting a cell in grid by fetching the selected value. I have tried this by including bound field in my grid like
<asp:GridView ID="GDV_1" runat="server" EnableModelValidation="true" AutoGenerateColumns="false" OnSelectedIndexChanged="GDV_1_SelectedIndexChanged" AutoGenerateSelectButton="false" DataKeyNames="SROID">
<Columns>
<asp:BoundField DataField="SRONameinEnglish" HtmlEncode="False" DataFormatString="<a target='_blank' href='Test.aspx?code={0}>ClickHere</a>" />
</Columns>
</asp:GridView>
Doing this way my requirement is achieved but the all cells are displaying Common text Click here instead of showing data from Database.
Please give your suggestion on how to get the value from database into cell and make it clickable. I don't want to use Select button. Please find my current output.
This is my current output I want my data from DB instead of ClickHere.
You can use TemplateField
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnk<%# Eval("SRONameinEnglish")%>"><%# Eval("SRONameinEnglish")%></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and click of LinkButton put your code to navigate anywhere.
In your case you are binding boundfield with static a tag which have href attribute so your not able to change text on that boundfield from your database.To get your approach you should
use TemplateField and bind data with text attribute using eval keyword as below example.
Try it:
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
OR
you can also bind link with your hyperlink using NavigateUrl property of hyperlink as below example.
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink id="HyperLink2" NavigateUrl='<%#Eval("YourUrl") %>' Text='<%#Eval("name") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
I hope it will helpful to you.

How to access Dataset from.cs to .aspx using eval()

I am coding Gridview programmatically.
I have dataset in code behind part(.cs),when i am trying to access the dataset in .aspx page using Eval() "Error Creating Control" error is coming.
Is it the Right way using Eval()?
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblGridTier" runat="server" Text='<%#Eval(dt.Tables[0].Columns["Tier"])%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
If you are doing something like this in the code behind to bind the GridView (and you actually should do something like this):
DateSet ds = ...
GridView1.DataSource = ds;
GridView1.DataBind();
then the correct way to use eval is to give it just the name of the column you want to show.
Text='<%#Eval("Tier")%>'
ok please note html is rendered first then your code behind file is called. Now here dataset is null (not yet created) when HTML is being rendered dataset is null so control will not be created and an exception will be thrown. You can use this work around on Page_Load you can set text property of label or check here if dataset is null then don't assign value using Eval. Hope it will help.
Eval function evaluates fields directly from the selected table of datasource which your grid is bound with. A couple of examples as follows:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblSomeField" runat="server" Text='<%# Eval("field1")%>'></asp:Label>
<asp:Image ID="lblImageLink" runat="server" ImageUrl='<%# Eval("imagefield", "http://somelink.com/images/{0}")%>' />
<asp:HyperLink ID="lblMember" runat="server" NavigateUrl='<%# "/member.aspx?id=" + Eval("id") %>' Text='<%# Eval("membername") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>

how to add a link button in the grid view by visual studio?

I want to add a link button in grid view that will navigate to the next form in the website. but i want to know how to insert that button into the grid view column? please help me..
You can add Link buttons in the Item template of a gridview.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Link" runat="server" PostBackUrl="MyNextPage.aspx">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
// TEXT FOR COLUMN NAME
</HeaderTemplate>
<ItemTemplate>
// ADD LINK BUTTON HERE.
</ItemTemplate>
</asp:TemplateField>
</Columns>
Add this inside grid view.
try this
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:ButtonField ButtonType="Link" HeaderText="LinkButton"/>
</Columns>
</asp:GridView>
Make Sure your GridViews datasource is bound. Set Auto-Generate Columns to false.
Open GridViewTask , add new column with Hyperlink Field proper name and path . You are done.

Is there a way to insert Html into a gridview row?

Using aspnet 3.5, c# - Is there a way to insert Html into a gridview row?
Yes. Use the TemplateField, and then type your html directly into the markup. If the html is suppose to be dynamically created I would use a Literal instead of a Label.
<asp:GridView id="GridView1" runat="server">
<Columns>
<asp:TemplateField headertext="Column1">
<ItemTemplate>
<br />
<h1>
<%# Eval ("DataColumnName") %>
</h1>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField headertext="Column2">
<ItemTemplate>
<asp:Literal id="Literal1" runat="server" text='<%# Eval ("DataColumnName2") %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Simply modify the Text property of a cell.
I haven't tested this, but you should be able to add a Label control to the GridView cell. Then write your HTML to the Label's Text property. The Label should render the HTML.

Categories