I've been looking for a solution to this problem for a while, and I have searched the net, but still can't get this to work. If I put my code in the default asp template it will work, but when I use my template I always get the listbox Selecetedindex as -1.
Here is my C# code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web.UI.WebControls;
public partial class permissaotop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Droptopicoperfil_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=Server;Initial Catalog=Forum;uid=user;pwd=password;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "SP_vertopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
SqlDataReader rdr = comm.ExecuteReader();
lbpermitidotp.DataSource = rdr;
lbpermitidotp.DataTextField = "Nome";
this.lbpermitidotp.DataValueField = "Id";
lbpermitidotp.DataBind();
rdr.Close();
conn.Close();
conn.Open();
SqlCommand comm1 = conn.CreateCommand();
comm1.CommandType = CommandType.StoredProcedure;
comm1.CommandText = "[SP_naotopicoperfil]";
comm1.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
SqlDataReader rdr1 = comm1.ExecuteReader();
lbproibidotp.DataSource = rdr1;
lbproibidotp.DataTextField = "Nome";
this.lbproibidotp.DataValueField = "Id";
lbproibidotp.DataBind();
rdr1.Close();
conn.Close();
}
protected void BtnnaopermitirClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=NEVETS-LAPTOP\\NEVETS;Initial Catalog=Forum;uid=sa;pwd=sql;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "usp_inserirtopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
comm.Parameters.AddWithValue("#id_perfil", this.lbproibidotp.SelectedValue.ToString());
SqlDataReader rdr = comm.ExecuteReader();
if (this.lbproibidotp.SelectedIndex >= 0)
{
this.lbproibidotp.Items.RemoveAt(this.lbproibidotp.SelectedIndex);
}
lbpermitidotp.DataBind();
lbproibidotp.DataBind();
Droptopicoperfil.DataBind();
rdr.Close();
conn.Close();
Droptopicoperfil_SelectedIndexChanged(this, null);
}
protected void BtnpermitirClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=NEVETS-LAPTOP\\NEVETS;Initial Catalog=Forum;uid=sa;pwd=sql;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "SP_apagartopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
comm.Parameters.AddWithValue("#id_perfil", lbpermitidotp.SelectedValue.ToString());
SqlDataReader rdr = comm.ExecuteReader();
lbpermitidotp.DataSource = rdr;
if (this.lbpermitidotp.SelectedIndex >= 0)
{
this.lbpermitidotp.Items.RemoveAt(this.lbpermitidotp.SelectedIndex);
}
lbpermitidotp.DataBind();
lbproibidotp.DataBind();
Droptopicoperfil.DataBind();
rdr.Close();
conn.Close();
Droptopicoperfil_SelectedIndexChanged(this, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
//testing listbox
Label3.Text =lbproibidotp.SelectedIndex).ToString();
//Always gets the result -1
}
}
Asp:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="permissaotop.aspx.cs" Inherits="permissaotop" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server">
<br />
<asp:Panel ID="pnlperfil" runat="server" GroupingText="Topicoperfil"
style="text-align: center; margin-top: 15px;"
ScrollBars="None" Height="607px"
HorizontalAlign="Center" Wrap="False" EnableTheming="False"
Direction="LeftToRight" Font-Size="Small" Width="711px">
<br />
<br />
<table align="left">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Perfil"></asp:Label>
<br />
</td>
<td>
<asp:DropDownList ID="Dropperfil" runat="server" Height="20px" Width="213px"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Nome"
DataValueField="Id" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString2 %>"
SelectCommand="SELECT * FROM [Perfil]"></asp:SqlDataSource>
<br />
</td>
<td>
</td>
</tr>
<tr>
<td >
<asp:Label ID="Label2" runat="server" Text="topico"></asp:Label>
<br />
</td>
<td >
<asp:DropDownList ID="Droptopicoperfil" runat="server" Height="19px"
style="margin-left: 3px" Width="213px" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="nome" DataValueField="Id_topico"
>
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString2 %>"
SelectCommand="SELECT * FROM [Topico]"></asp:SqlDataSource>
<br />
</td>
<td >
</td>
</tr>
<tr>
<td >
<asp:ListBox ID="lbpermitidotp" runat="server" Width="113px"
onselectedindexchanged="lbpermitidotp_SelectedIndexChanged"
ViewStateMode="Enabled"></asp:ListBox>
</td>
<td >
<asp:Button ID="btnproibirtp" runat="server" style="text-align: center"
Text=">>" onclick="BtnpermitirClick" />
<asp:Button ID="btnpermitirtp" runat="server" Text="<<"
onclick="BtnnaopermitirClick" />
<asp:Label ID="Label3" runat="server" style="background-color: #000000"
Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</td>
<td >
<asp:ListBox ID="lbproibidotp" runat="server" Width="100px"
ViewStateMode="Enabled"></asp:ListBox>
<br />
<br />
</td>
</tr>
</table>
</asp:Panel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="AfterBody" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="Footer" Runat="Server">
</asp:Content>
How can I fix this?
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 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 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
{
}
}
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
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 />