Fileupload Image not getting inserted.. - c#

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 />

Related

How to insert data in table in asp.net

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 need to Show the data from database into my gridview on aspx webform page

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

Concatenating more than one columns in SQL Server

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
{
}
}

Count of likes for image

i am creating an image gallery (images stored in Images folder,path saved in db) in the gridview
Each imagename is saved in dbwith and uinque id and the columnname : storyid.
can anyone tell me how to bind the indiviudal images "like" count in the lblcount
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="SM1">
</asp:ScriptManager>
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
OnRowCommand="GridView1_RowCommand1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="IncreaseButton" Text="Like" CommandName="Increase"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:Label runat="server" ID="lblCount"></asp:Label>
<div style="display: none;">
<asp:Label Text="<%#Bind('StoryId')%>" ID="lblStoryid" runat="server"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageUrlField="FilePath" ControlStyle-Width="100" ControlStyle-Height="100"
HeaderText="Preview Image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="Description" runat="server" Visible="False"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label Text="<%#Bind('Description')%>" ID="lblImageid" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
public partial class Gallery : System.Web.UI.Page
{
private void bindimage()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["dbconnection"].ConnectionString;
string strQuery = "select * from story";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Increase")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label listPriceTextBox = (Label)row.FindControl("lblStoryid");
int storyId = Convert.ToInt32(listPriceTextBox.Text);
string UserEmailid = "aditya.arjula#gmail.com";
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "INSERT INTO Likes(storyId,UserEmailid) VALUES(#storyId,#UserEmailid)";
string LikeCount = "SELECT COUNT(StoryId) FROM Likes Where StoryId=1001;;";
Label lblStoryid = (Label)row.FindControl("lblStoryid");
lblStoryid.Text = LikeCount;
SqlCommand cmd = new SqlCommand(strQuery);
SqlCommand cmdl = new SqlCommand(LikeCount);
cmdl.CommandType = CommandType.Text;
cmdl.Connection = con;
cmd.Parameters.AddWithValue("#storyId", storyId);
cmd.Parameters.AddWithValue("#UserEmailid", UserEmailid);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
cmdl.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
}
You just need to pull the number of likes out when you pull the story record down in your bindimage method e.g.
SELECT Story.StoryId, Max(Description) As Description, Count(Likes.StoryId) as LikeCount from Story
INNER JOIN Likes On Likes.StoryId = Story.StoryId
GROUP BY Story.StoryId
Then you can bind the count like
<asp:Label Text='<%# Bind("LikeCount")%>' runat="server" ID="lblCount"></asp:Label>
See this fiddle.

How to Edit,Update and Delete Rows in GridView in ASP.NET

I am retrieving Data From Database into GridView.
I don't know how to Edit and Delete row in GridView and it Also Update in Database.
Also please Tell me if their is any mistake in my Code
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 248px;
}
.style2
{
width: 100%;
}
.style3
{
height: 180px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style3">
<h1 align="center">Students Personal Information
</h1>
<table class="style2">
<tr>
<td class="style1">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Button ID="Button1" runat="server" Text="Insert Data"
onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Students" Width="128px" />
</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
enter code here
And my back-end code 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.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=DATA_NET_81_SOF;Initial
Catalog=Students;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Student's Name";
Label2.Text = "Student's Class";
Label3.Text = "Student's Roll Number";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", conn);
conn.Open();
cmd.Parameters.AddWithValue("StudentName", TextBox1.Text);
cmd.Parameters.AddWithValue("StudentClass", TextBox2.Text);
cmd.Parameters.AddWithValue("StudentRollno", TextBox3.Text);
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand sql = new SqlCommand("Select * from Personalinfo", conn);
SqlDataAdapter da = new SqlDataAdapter(sql);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = (ds);
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
}
private string connection = #"...";
protected void Button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connection))
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
}
For Update -->
protected void Button_Update(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "UPDATE Personalinfo SET StudentName = #1 ... WHERE Student_Id= #N";
cmd.Parameters.Add("#1",SqlDbType.NVarChar).Value = your_value;
cmd.Para.....
cmd.Parameters.Add("#N",.....).Value = your_student_id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
For Delete -->>
protected void Button_Delete(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Personalinfo WHERE StudentName = '"+TextBox1.Text+"'";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
After every event of button you can make a BindGrid ... to refresh your data from data grid... in BindGrid method you need to remake the select method you just did ... if you have issue tell me

Categories