I have a query in which I have to add more than one column.
Result of query is stored DataTable and binding it to Repeater. But the problem is DataTable shows the columns name and not the names I specified in query.
HTML (Persons.aspx):
<body>
<form id="form1" runat="server">
<h1><b>Persons</b></h1>
<div style="float:right">
<asp:LinkButton ID="lnkAdd" runat="server" Text="Add" Style="margin-right:100px"></asp:LinkButton>
</div>
<br />
<br />
<asp:Repeater ID="rptPersons" runat="server">
<ItemTemplate>
<div style="float: left">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Pic") %>' Width="100px" Height="100px" />
</div>
<div style="float:left;margin-left:10px;">
<asp:Label ID="lblName" runat="server" Text='<%# Eval("PersonName") %>'></asp:Label><br />
<asp:Label ID="lblPost" runat="server" Text='<%# Eval("Post") %>'></asp:Label><br />
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("Location") %>'></asp:Label><br />
<%--<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label><br />--%>
</div>
</ItemTemplate>
<SeparatorTemplate>
<div style="margin-left:20px"></div>
</SeparatorTemplate>
</asp:Repeater>
</form>
</body>
Stored procedure:
select
FirstName as PersonName,
ISNULL(Designation,'') + ',' + ISNULL(Organization,'') as Post,
ISNULL(tblPersons.City,'') + ',' + ISNULL(tblPersons.State,'') as Location,
GETDATE() - tblPersons.dob + '( DoJ :' + '' + ISNULL(tblPersons.doj,'') as Age,
tblPersons.photo_name as Pic
from
tblpersons
Logic class:
public class PersonsLogic
{
public DataTable GetPersons()
{
string Connection = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(Connection))
{
SqlCommand cmd = new SqlCommand("spGetPersons", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
}
}
Persons.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Persons objPerson = new Persons();
PersonsLogic objLogic = new PersonsLogic();
DataTable dt = objLogic.GetPersons();
if (dt.Rows.Count > 0)
{
rptPersons.DataSource = dt;
rptPersons.DataBind();
}
else
{
}
}
Related
Now I found a new way just need help on it please. Basically, I am to insert a product data into database from product_desc.aspx page when the user clicks of add to cart button. So when I run the following code I get this error message. Please help me to solve this problem, Thanks. Help is appreciated.
Error:
{"Object reference not set to an instance of an object."}
my Product_desc.aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Repeater ID="d1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div style="height:300px; width:600px; border:1px solid black; margin-left:250px;">
<div style="height:300px; width:200px; float:left; border:1px solid black;">
<img src="data:image;base64,<%# Convert.ToBase64String((byte[])Eval("Image")) %>" />
</div>
<div style="height:300px; width:350px; float:left; border:1px solid black;">
Coffee Name:
<asp:Label ID="CoffeeNameLabel" runat="server" Text='<%# Eval("CoffeName") %>' />
<br />
Coffee Strength
<asp:Label ID="CoffeeStrengthLabel" runat="server" Text='<%# Eval("CoffeeStrength") %>' />
<br />
Coffee Grind
<asp:Label ID="CoffeeGrindLabel" runat="server" Text='<%# Eval("CoffeeGrind") %>' />
<br />
Origin
<asp:Label ID="CoffeeOriginLabel" runat="server" Text='<%# Eval("Origin") %>' />
<br />
Quantity
<asp:Label ID="CoffeeQuantityLabel" runat="server" Text='<%# Eval("Quantity") %>' />
<br />
Price
<asp:Label ID="CoffeePriceLabel" runat="server" Text='<%# Eval("Price") %>' />
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="b1" runat="server" Text="Add To Cart" onClick="b1_Click" />
</asp:Content>
Product_desc.aspx.cs page code
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("ordercoffee.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
cons.Open();
SqlCommand cmd = cons.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from coffeeshop where Id="+id+"";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
cons.Close();
}
}
protected void b1_Click(object sender, EventArgs e)
{
//double p = double.Parse((string)ViewState["Price"]);
string cimg = ViewState["Image"].ToString();
string cname = ViewState["CoffeName"].ToString();
string cstrength = ViewState["CoffeeStrength"].ToString();
string cgrind = ViewState["CoffeeGrind"].ToString();
string corigin = ViewState["Origin"].ToString();
string cprice = ViewState["Price"].ToString();
string cquantity = ViewState["Quantity"].ToString();
//string s2 = System.Web.HttpContext.Current.User.Identity.Name;
string s1 = Request.QueryString["id"];
cons.Open();
SqlCommand cmd = cons.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO cart (CoffeeOrderId, CoffeeName, Strength, Grind, Origin, Quantity, Price, Image) VALUES(#orderid, #name, #strength, #grind, #origin, #quantity, #price, #image)";
cmd.Parameters.AddWithValue("#orderid", s1);
cmd.Parameters.AddWithValue("#name", cname);
cmd.Parameters.AddWithValue("#strength", cstrength);
cmd.Parameters.AddWithValue("#grind", cgrind);
cmd.Parameters.AddWithValue("#origin", corigin);
cmd.Parameters.AddWithValue("#quantity", cquantity);
cmd.Parameters.AddWithValue("#price", cprice);
cmd.Parameters.AddWithValue("#image", cimg);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cons.Close();
Response.Redirect("login.aspx");
}
First define the Sql Column to Binary or VarBinary data type depending on your need
then convert the image to byte array
byte[] imageByteArray;
using(var ms = new MemoryStream())
{
yourImage.Save(ms, yourImage.RawFormat);
imageByteArray = ms.ToArray();
}
now you can just do
cmd.Parameters.AddWithValue("#image", imageByteArray);
I am trying to use grid view to display a join of several tables(Empdetail,Department,Country,State,City,Qualification). The main table(Empdetail) has different IDs(eg DeptID) which refer to the primary key ID present in the tables. I want department(and other fields) to appear as dropdown choice while updating the gridview but I am facing issues while populating the drop down list and making the edit button fire. The following is the code.
.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Database.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employee Database</title>
<script src="Themes/js/bootstrap.js" type="text/javascript"></script>
<script src="Themes/js/jquery.min.js" type="text/javascript"></script>
<script src="Themes/js/npm.js" type="text/jahttp://www.aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspxvascript"></script>
<script src="Themes/js/bootstrap.min.js" type="text/javascript"></script>
<script type = "text/javascript" src = "Scripts/jquery-1.3.2.min.js"></script>
<script type = "text/javascript" src = "Scripts/jquery.blockUI.js"></script>
<script type = "text/javascript">
//to create a loading effect
function BlockUI(elementID) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function() {
$("#" + elementID).block({ message: '<table align = "center"><tr><td>' +
'<img src="Images/loadingAnim.gif"/></td></tr></table>',
css: {},
overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'
}
});
});
prm.add_endRequest(function() {
$("#" + elementID).unblock();
});
}
$(document).ready(function() {
BlockUI("dvGrid");
$.blockUI.defaults.css = {};
});
</script>
<link href="Themes/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap-theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id = "dvGrid">
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "900px" AlternatingRowStyle-BackColor = "#b3e6ff"
AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound"
HeaderStyle-BackColor = "#0080ff" DataKeyNames="ID"
PageSize="10" class="table table-bordered" ShowFooter="true"
onrowediting="EditEmployee" onrowupdating="UpdateEmployee"
onrowcancelingedit="CancelEdit" OnRowDeleting="DeleteEmployee"
EmptyDataText="No records Selected.">
<Columns >
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%# Eval("ID") %>' /><!--Primary key,no update and insert,auto generated-->
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "EmpCode">
<ItemTemplate>
<asp:Label ID="lblEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmpCode" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "DOJ">
<ItemTemplate>
<asp:Label ID="lblDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDOJ" class="form-control" Width = "100px"
MaxLength = "15" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "120px" HeaderText = "Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server"
Text='<%# Eval("DeptName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox class="form-control" ID="txtDepartment" Width = "140px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%# Eval("CoName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCountry" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server"
Text='<%# Eval("SName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtState" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%# Eval("CiName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCity" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Qualification">
<ItemTemplate>
<asp:Label ID="lblQualification" runat="server"
Text='<%# Eval("QName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQualification" class="form-control" Width = "80px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("ID")%>' OnClick = "DeleteEmployee"
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" >
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
class="btn-primary" type="button" OnClick = "AddNewEmployee"/>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Codebehind(aspx.cs/c#)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
//Find the DropDownList in the Row
SqlConnection con = new SqlConnection(constr);
DropDownList Depddl = (DropDownList)e.Row.FindControl("Depddl");
string query = "SELECT ID,DeptName FROM Department;";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
Depddl.DataSource = GetData(cmd);
Depddl.DataTextField = "DeptName";
Depddl.DataValueField = "ID";
Depddl.DataBind();
con.Close();
//Add Default Item in the DropDownList
Depddl.Items.Insert(0, new ListItem("Please select"));
//Select the Department ofEmployee in DropDownList
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
}
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string city = (GridView1.Rows[e.RowIndex].FindControl("Depddl") as DropDownList).SelectedItem.Value;
string ID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblID")).Text;
string EmpCode = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtEmpCode")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string DOJ = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtDOJ")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Empdetail set EmpName=#EmpName," + "EmpCode=#EmpCode,"+ "DOJ=#DOJ where ID=#ID; " +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, "+
"Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID "+
"JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID "+
"JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = EmpCode;
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#DOJ", SqlDbType.VarChar).Value = DOJ;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Empdetail where " +
"ID=#ID;" +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private void BindData()
{
string query = "select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ,"+
"Department.ID, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID"+
" JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID"+
" JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void AddNewEmployee(object sender, EventArgs e)
{
string ID = ((TextBox)GridView1.FooterRow.FindControl("txtID")).Text;
string EmpCode = ((TextBox)GridView1.FooterRow.FindControl("txtEmpCode")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
/*cmd.CommandText = "insert into Empdetail(EmpCode, CompanyName) " +
"values(#CustomerID, #ContactName, #CompanyName);" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value = CustomerID;
cmd.Parameters.Add("#ContactName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Company;*/
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
Note:- I have searched extensively and on multiple sites so I would really appreciate it if you can tell me the exact issue instead of navigating me to a link. I am new to the concept of Gridview so please critique the code with an open mind. Thanks in advance
In the aspx file I'd drop data sources for each dropdown, SqlDataSource for example. In the markup you can fully define each DDL and every row uses the same single instance of the datasource. On editing you need only capture the selected value to update.
So...the DataSource for the Department example...
. . .
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="SELECT ID,DeptName FROM Department"
EnableCaching="True">
</asp:SqlDataSource>
Then in the GridView Template for Department...
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
DataSourceID="SqlDataSource1"
DataTextField="DeptName"
DataValueField="ID"
</asp:DropDownList>
</EditItemTemplate>
And in the code behind you can optionally select the current value for the DDL from a current value...or not...up to you.
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( e.Row.RowState.HasFlag( DataControlRowState.Edit ) )
{
DataRowView drv = (DataRowView) e.Row.DataItem;
DropDownList ddl = (DropDownList) e.Row.FindControl( "DropDownList1" );
ddl.SelectedValue = ((int) drv[ "ID" ]).ToString();
}
}
}
After commenting several segments of the code I realized that the issue was with the "OnRowDataBound" function.
Commenting these lines made the update button fire again:-
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
What I could gather from this is that I cannot access an Item template control that way. Commenting the lines made the page run smoothly. However it was at the cost of losing the functionality of auto-selecting the original data value. I would like to implement this and will post an update as soon as I can achieve this.
I want to fetch the data from the sql server database and show it into the gridview which i have created on my aspx webform page but it's not fetching it instead it's throwing an error that says **A field or property with the name 'Name' was not found on the selected data source.
** I already have a data row into my database with values under column name and i have created gridview columns in my code but that doesn't seem to work.Please help me get through with this problem.Below is my whole code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Welcome To My First Web Form<br />
<h1> Candidate Registration Form</h1>
<br />
<br />
Applicant's Name:
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="True" EnableViewState="False" ValidateRequestMode="Enabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter Your Name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Applicant's FName"></asp:Label>
:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please enter your Father name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>: <asp:RadioButtonList ID="gender" RepeatDirection="Horizontal" runat="server" Width="141px" RepeatLayout="Flow"> <asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="gender" ErrorMessage="Please Choose your Gender" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="E-mail ID"></asp:Label>
:
<asp:TextBox ID="TextBox3" runat="server" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail address is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail addresses must be in the format of name#domain.xyz" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red">Invalid Format</asp:RegularExpressionValidator>
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="password"></asp:Label>
:
<asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="TextBox4" Display="Dynamic" ErrorMessage="Password is Required!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="Confirm Password"></asp:Label>
:
<asp:TextBox ID="TextBox5" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="The passwords Didn't Match!" ForeColor="Red" ControlToCompare="TextBox4" Display="Dynamic"></asp:CompareValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:BoundField DataField="Name" />
<asp:BoundField DataField="FatherName" />
<asp:BoundField DataField="Email" />
</Columns>
</asp:GridView>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
Below is the code for cs file behind:
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;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\admin\documents\visual studio 2013\Projects\WebApplication5\WebApplication5\App_Data\Candidates.mdf;Integrated Security=True");
public static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
//DataTable dt = new DataTable();
//dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("FatherName"), new DataColumn("E-mail") });
//ViewState["Candidates"] = dt;
//GridView1.DataSource = (DataTable)ViewState["Candidates"];
//GridView1.DataBind();
}
}
protected void gvbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Candidates", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
count += 1;
int rowIndex = 0;
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Candidates values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
//if (count > 1)
//{
// DataTable dtCurrentTable = (DataTable)ViewState["Candidates"];
// DataRow drCurrentRow = null;
// if (dtCurrentTable.Rows.Count > 0) {
// //for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
// //{
// drCurrentRow = dtCurrentTable.NewRow();
// int totalrows = dtCurrentTable.Rows.Count;
// dtCurrentTable.Rows.Add(drCurrentRow);
// dtCurrentTable.Rows[totalrows]["Name"] = TextBox1.Text;
// dtCurrentTable.Rows[totalrows]["FatherName"] = TextBox2.Text;
// dtCurrentTable.Rows[totalrows]["E-mail"] = TextBox3.Text;
// rowIndex++;
// //}
// ViewState["Candidates"] = dtCurrentTable;
// GridView1.DataSource = dtCurrentTable;
// GridView1.DataBind();
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// }
//}
//else
//{
// DataTable dt = (DataTable)ViewState["Candidates"];
// dt.Rows.Add(TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim());
// ViewState["Candidates"] = dt;
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// BindGrid();
//}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//protected void BindGrid()
//{
// //GridView1.DataSource = (DataTable)ViewState["Candidates"];
// //GridView1.DataBind();
//}
}
}
Just ignore those commented codes,and that error which i mentioned comes when i debug the code on line Gridview1.DataBind(); in method gvbind().
<asp:BoundField DataField="Cname" />
<asp:BoundField DataField="Cfname" />
<asp:BoundField DataField="Cmail" />
this will work
I have a richtextbox and a gridview.
When I enter the data into the richtextbox, it should be displayed in a gridview and saved in database.
Now my requirement is that, if i am entering a paragraph or a large amount of data I should display a "readmore" button, that when clicked, display the complete data.
<%# Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" />
<br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
c# code-
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(#Richtextbox)", con);
cmd.Parameters.AddWithValue("#Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
first in your select query add id of your text(your primary key of table RichTextBoxData)
and in gridview make it,s visible =false like this
<asp:TemplateField HeaderText="id" InsertVisible="False" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and then
protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lb =e.Row.FindControl("lbltxt") as Label;
if (lb.Text.Length > 15)//any length u want
{
DataRow drv = ((DataRowView)e.Row.DataItem).Row;
int tempID = Convert.ToInt32(drv["id"].ToString());
HyperLink hp = new HyperLink();
hp.Text = "read more";
hp.NavigateUrl = "~/mydetails.aspx?id=" + tempID;
e.Row.Cells[1].Controls.Add(hp);
lb.Text = lb.Text.Substring(0, 15);
}
}
}
and on page_load of mydetails.aspx make
query to select RichTextData where id=request.querystring["id"]
I have an ASP.NET FileUpload control. In the code-behind file, I used class to insert values-
public void Insertcert()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
if (FileUpload1.HasFile)
{
byte[] productImage = FileUpload1.FileBytes;
String insertstring2 = #"insert into Cert(CertName, CertLogo)
values(#CertName, #CertLogo)";
SqlCommand cmd = new SqlCommand(insertstring2, conn);
cmd.CommandText = insertstring2;
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#CertName", TextBox18.Text);
cmd.Parameters.Add("#CertLogo", SqlDbType.VarBinary).Value = productImage;
cmd.ExecuteNonQuery();
}
}
finally
{
conn.Close();
}
Executing it here-
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
Insertcert();
}
I am using Wizard control to insert Certifications of the Employee:
<asp:Wizard ID="Wizard1" runat="server"
OnFinishButtonClick="Wizard1_FinishButtonClick"
Width="266px" ActiveStepIndex="0">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Step 2">
<asp:Label ID="Label19" class="caption" runat="server" Text="Certification Name:"></asp:Label>
<asp:TextBox ID="TextBox18" class="box" runat="server"></asp:TextBox> <br /><br />
<asp:Label ID="Label20" class="caption" runat="server" Text="Certification Logo:"></asp:Label>
<asp:FileUpload ID="FileUpload1" class="box" runat="server" /> <br /><br />