How can I render links in columns of WebForms GridView?
I have the following code
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.UsersContacts WHERE UserId='vika'", con);
con.Open();
var list1 = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var node = reader[1];
list1.Add(node.ToString());
}
}
con.Close();
GridView1.DataSource = list1;
GridView1.DataBind();
and I want to do something such as list1.Add("<a href='#'>"+node.ToString()+"<a>"); and make it a link in my GridView.
I would rather do this at the gridview template definition instead of passing the link from the datasource. Your gridview definition can have the asp:HyperLinkField or asp:HyperLink field and bind the data as required.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperLinkField
HeaderText="View Details"
DataNavigateUrlFields="node"
DataNavigateUrlFormatString="~/TargetPage.aspx?Id={0}"
DataTextField="node"
/>
</Columns>
</asp:GridView>
Or
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("node", "~/TargetPage.aspx?Id={0}") %>' Text="View Details" />
Related
I currently have two dropdown lists and they are populated with names from a database. What I want to do is have a player be selected, and then on a button click, the data from the table is populated into a gridview. Right now I am just getting a "No data returned" message and I cannot figure out why.
<asp:DropDownList ID="ddl_QB1" runat="server" Width="200px" AppendDataBoundItems="True"
AutoPostBack="True" Height="16px" DataTextField="Player" DataValueField="id" ></asp:DropDownList>
<asp:Gridview ID="GridView1" runat="server" AutoGenerateColumns="false" Visible="true"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px"
CellPadding="4" GridLines="Horizontal" ShowHeaderWhenEmpty="True" EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Total Points">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("[Pts]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Pts") %>'>
</asp:Label>
</ItemTemplate>
protected void Page_Load(object sender, EventArgs e)
{
LoadQuarterbacks();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] from Quarterbacks", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddl_QB1.DataSource = dt;
ddl_QB1.DataBind();
}
}
private void LoadQuarterbacks()
{
ddl_QB1.Items.Clear();
ddl_QB2.Items.Clear();
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("SELECT id, Player FROM Quarterbacks", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("Quarterbacks");
da.Fill(ds); // fill dataset
ddl_QB1.DataTextField = ds.Tables[0].Columns["Player"].ToString(); // text field name of table dispalyed in dropdown
ddl_QB2.DataTextField = ds.Tables[0].Columns["Player"].ToString();
ddl_QB1.DataValueField = ds.Tables[0].Columns["id"].ToString();
ddl_QB2.DataValueField = ds.Tables[0].Columns["id"].ToString(); // to retrive specific textfield name
ddl_QB1.DataSource = ds.Tables[0];
ddl_QB2.DataSource = ds.Tables[0];
ddl_QB2.DataBind();//assigning datasource to the dropdownlist
ddl_QB1.DataBind(); //binding dropdownlist
con.Close();
ddl_QB1.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
ddl_QB2.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionstring);
string query = "SELECT [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] FROM Quarterbacks where id=" + ddl_QB1.SelectedValue;
SqlDataAdapter sda = new SqlDataAdapter(query,con);
con.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Following 3 changes would give desired results.
First - AutoPostBack should be set to false on the dropdown element as that is causing postback even before you click on the button.
Second - remove the current code inside if(!Page.IsPostback). This code is not necessary. Also, this code is not setting DataTextField and DataValueField properties for ddl_QB1 and ddl_QB2.
Third - put the method call LoadQuarterbacks() inside if(!Page.IsPostback). We do not have to bind these values for ddl_QB1 and ddl_QB2 on each request.
If a refresh is required on the dropdown controls, then call LoadQuarterbacks() method after binding the gridview at the end of the button click. That way you are capturing the selected values from dropdown before rebinding the them. Rebinding the DropDowns would cause them loose the selected values.
I am trying to get the StudentFirstName from data base and show in the text box right now am using grid view where it shows the data but not in textbox am not sure how to get all the data from data base and show in individual text box.
MyDB
StudentFirstName SchoolID StudCourse
abc sc123 A
cef sc155 A
gij sc133 A
abc sc122 B
cef sc156 B
gij sc144 B
C#
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select StudentFirstName from student WHERE StudCourse=#DDSelected_Class order by StudentFirstName ASC";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#DDSelected_Class", DDSelected_Class);
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader == null || !oReader.HasRows)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);
}
else
{
while (oReader.Read())
{
GridView1.DataSource = oReader;
GridView1.DataBind();
}
}
myConnection.Close();
}
}
Gridview
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
You will need to define ItemTemplate for your column. It will contain a textbox and the field name name in Eval to bind it.
Complete code sample:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("StudentFirstName ") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<Columns>
</asp:GridView>
I have a gridview which contains textboxes and dropdowns.In gvScheduleBattingScore_RowDataBound Event I am binding dropdowns without any problem. The button control is outside to the gridview. I actually want to submit all the textbox values and dropdown selected values to the database on buttonclickevent But I don't know where I am going wrong.
The Problem is Textboxes do not contain any text and am getting Exception
Input string was not in a correct format.
Please help me out...
<asp:GridView ID="gvScheduleBattingScore" runat="server" AllowSorting="false" AutoGenerateColumns="False" AllowPaging="false"
GridLines="None" CellPadding="1" CssClass="GridViewStyle" ShowFooter="false" width="100%"
OnRowDataBound="gvScheduleBattingScore_RowDataBound">
<Columns>
<asp:BoundField DataField="P_PlayerId" HeaderText="Player Id" HeaderStyle-Wrap="true" HeaderStyle-Width="5%" Visible="false"/>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" HeaderStyle-Wrap="true" HeaderStyle-Width="30%"/>
<asp:TemplateField HeaderText="Playing Order" HeaderStyle-Wrap="true" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtPlayingOrder" runat="server" CssClass="TinyTexBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bold By">
<ItemTemplate>
<asp:DropDownList ID="ddlBoldBy" runat="server"> </asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</br>
<asp:Button ID="ButtonAdd" runat="server" Text="Add" CssClass="SmallButton"
ValidationGroup="Add" onclick="ButtonAdd_Click"/>
On ButtonClick Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlConnection dBConnection = null;
try
{
int playerId;
short plyerOrder;
string BatsmanStatus;
int boldBy;
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["CriConn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_InsertScores", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow GVRow in gvScheduleBattingScore.Rows)
{
string textPlayerId = GVRow.Cells[0].Text;
TextBox textPlyerOrder = (TextBox)GVRow.Cells[1].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = GVRow.Cells[2].FindControl("txtStatus") as TextBox;
DropDownList DropDownBoldBy = (DropDownList)GVRow.Cells[18].FindControl("ddlBoldBy");
playerId = Convert.ToInt32(textPlayerId );
if (!string.IsNullOrEmpty(textPlyerOrder.Text))
plyerOrder = Convert.ToInt16(textPlyerOrder.Text);
if (!string.IsNullOrEmpty(textBatsmanStatus.Text))
BatsmanStatus = textBatsmanStatus.Text;
if (!string.IsNullOrEmpty(DropDownBoldBy.SelectedValue) && DropDownLbwBy.SelectedValue != "Select")
boldBy = Convert.ToInt32(DropDownBoldBy.SelectedValue);
cmd.Parameters.Add("#PlayerId", SqlDbType.NVarChar).Value = playerId;
cmd.Parameters.Add("#PlayerId", SqlDbType.Int).Value = playerId;
cmd.Parameters.Add("#plyerOrder", SqlDbType.Int).Value = plyerOrder;
cmd.Parameters.Add("#BatsmanStatus", SqlDbType.NVarChar).Value = BatsmanStatus;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
cmd.ExecuteNonQuery();
dBConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
As per the Chat discussion with #bhoopendra.sahoo, we come to the conclusion that it is a Binding issue.
When Button Click Event is fired, the GridView binds again causing the issue.
The fix is to bind the GridView only once and restrict its binding during other events.
Add a null checking before converting the textbox value to int
if (!string.IsNullOrEmpty(textPlayerId.Text))
playerId = Convert.ToInt32(textPlayerId);
Also make these changes to you code, to find the textbox controls in the correct cell
TextBox textPlyerOrder = (TextBox)GVRow.Cells[2].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = (TextBox)GVRow.Cells[3].FindControl("txtStatus");
I have a stored procedure in SQL that searches employee details. When it finds something,it returns and displays the data in a gridview. But how can I handle if it did not return anything? like when 'no record is found'?
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("[Reader].[usp_SearchUser]", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#empID", SqlDbType.Int).Value = this.EmpID;
con.Open();
int result = com.ExecuteNonQuery();
if (result == 0)
{
this.NoRecord = "No Record Found";
}
else
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
search.DataSource = ds;
search.DataBind();
}
}
}
Did not get what is your exact question? do you want the gridview property when there is no data then it will show as no records found i.e. EmptyDataText="No records Found"
e.g.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No records Found">
<Columns>
<asp:boundfield datafield="empID" headertext="Employee ID"/>
<asp:boundfield datafield="empName" headertext="Employee Name"/>
</Columns>
</asp:GridView>
I suppose you use a webcontrol GridView? So you might use the GridView.EmptyDataTemplate to have full control of what to render if no data has been bound.
<asp:gridview id="yourGridView" runat="server">
<emptydatatemplate>
No Data Found!
<img src="noData.jpg"/>
</emptydatatemplate>
</asp:gridview>
Or just use EmptyDataText Property if you just want to show a text Message
<asp:gridview id="yourGridView" emptydatatext="No Data Found" runat="server">
....
</asp:gridview>
I have a grid which is being bound in code behind in which i want to display template field also.
I am generating 3 columns in DataTable for grid view and the template field is TextBox control.
My code for binding data is..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class gr4 : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");
string query = "Select Capacity from Dealer_License_Capacity where ID='D00001' and Software_ID='001' and Version_ID='1'";
cn.Open();
cmd = new SqlCommand(query,cn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Software_Name", typeof(string));
dt.Columns.Add("Version_Name", typeof(string));
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
for (int i = 0; i < count; i++)
{
DataRow dr = dt.NewRow();
dr["Name"] = "aaa";
dr["Software_Name"] = "bbb";
dr["Version_Name"] = "ccc";
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
My source code for grid view is:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
The grid display template field as first column but I want to display the template field as last column in output. Can I add more template fields in this grid..??
Please help..
Thanks in advance
You can use bound fields like below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" > /*changed to false*/
<Columns>
<asp:BoundField HeaderText="Name"
DataField="Name"/>
<asp:BoundField HeaderText="SoftwareName"
DataField="Software_Name"/>
<asp:BoundField HeaderText="VersionName"
DataField="Version_Name"/>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change the order as you like.
if all ready data is there in database and column is there at the same way in grid-view column name is name there has to display name is order how me not getting
my grid code is this one but not coming order wise