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
Related
I have a record update page which seems to populate all the fields, however the dropdown lists will only list the data from that particular record, it is not listing the other School Names and the Student Names. The two dropdown lists are cascaded i.e. selecting the School Name ddl should list only the Students that are from that school in the Student ddl.
Any help on this will be much appreciated, thank you.
Gridview code on tours.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging" OnEditCommand="EditAddress" PageSize="5">
<Columns>
<asp:HyperLinkField Text="Update" DataNavigateUrlFields="TourId" DataNavigateUrlFormatString="~/abcrud1/tours_update.aspx?TourId={0}" />
<asp:BoundField DataField="TourId" HeaderText="TourId" HtmlEncode="false" />
<asp:BoundField DataField="VisitorName" HeaderText="VisitorName" HtmlEncode="false" />
<asp:BoundField DataField="VisitorSchoolId" HeaderText="VisitorSchoolId" HtmlEncode="false" />
<asp:BoundField DataField="SchName" HeaderText="SchName" HtmlEncode="false" />
<asp:BoundField DataField="TourDate" HeaderText="TourDate" HtmlEncode="false" />
<asp:BoundField DataField="StudentId" HeaderText="StudentId" HtmlEncode="false" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" HtmlEncode="false" />
<asp:BoundField DataField="LastName" HeaderText="LastName" HtmlEncode="false" />
</Columns>
</asp:GridView>
tour_update.aspx
<form id="form1" runat="server">
<div>
<table style="width: 50%;">
<tr>
<td style="width: 50%;">Tour Id:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourid" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor Name:</td>
<td style="width: 50%;">
<asp:TextBox ID="txtvisname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor School:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlvisschool" runat="server" AutoPostBack="true"></asp:DropDownList></td>
</tr>
<tr>
<td style="width: 50%;">Tour Date:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourdate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Student:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlstudent" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td><asp:Button ID="btnUpdate" Text="Update" runat="server" OnClick="TourUpdate_click" /></td>
<td></td>
</tr>
</table>
</div>
</form>
tour_update.aspx.cs
{
public partial class tours_update : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
{
if (!IsPostBack)
{
this.GetTour();
}
}
}
protected void TourUpdate_click(object sender, EventArgs e)
{
this.TourUpdate();
}
private int id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["TourId"]) ? int.Parse(Request.QueryString["TourId"]) : 0;
}
}
private void TourUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE tblCRUD1_Tour SET VisitorName=#VisitorName, VisitorSchoolId=#VisitorSchoolId, TourDate=#TourDate, StudentId=#StudentId WHERE TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.SelectedItem.Value);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.SelectedItem.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/abcrud1/tours.aspx");
}
}
}
private void GetTour()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName
FROM tblCRUD1_Tour
INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId
INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId
WHERE tblCRUD1_Tour.TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
this.txttourid.Text = dr["TourId"].ToString();
this.txtvisname.Text = dr["VisitorName"].ToString();
this.txttourdate.Text = dr["TourDate"].ToString();
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "VisitorSchoolId";
ddlvisschool.DataBind();
ddlstudent.DataSource = dt;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
}
}
}
}
}
}
}
tours_add.aspx.cs
{
public partial class tours_add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddlvisschool();
ddlstudent.Items.Insert(0, " Select Pupil ");
}
}
private void Bindddlvisschool()
{
con.Open();
string str = #"Select * FROM tblCRUD1_School ORDER BY SchName ASC";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "SchId";
ddlvisschool.DataBind();
ddlvisschool.Items.Insert(0, new ListItem(" Choose Last School ", "0"));
ddlvisschool.SelectedIndex = 0;
con.Close();
}
protected void TourAdd_click(object sender, EventArgs e)
{
con.Open();
string str = #"INSERT INTO tblCRUD1_Tour (VisitorName,VisitorSchoolId,TourDate,StudentId) VALUES (#VisitorName,#VisitorSchoolId,#TourDate,#StudentId)";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.Text);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.Text);
cmd.ExecuteNonQuery();
lblmessage1.Text = "Tour added successfully";
con.Close();
Response.AddHeader("REFRESH", "3;URL=tours.aspx");
}
protected void ddlvisschool_SelectedIndexChanged(object sender, EventArgs e)
{
string get_SchId;
string get_SchName;
get_SchId = ddlvisschool.SelectedValue.ToString();
get_SchName = ddlvisschool.SelectedItem.Text;
if (get_SchId != "0")
{
con.Open();
SqlDataAdapter da;
DataSet ds = new DataSet();
string query;
query = "SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName "
+ "FROM tblCRUD1_Tour "
+ "INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId "
+ "INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId "
+ "WHERE tblCRUD1_Tour.VisitorSchoolId='" + get_SchId.ToString() + "' ORDER BY tblCRUD1_Student.LastName ASC";
da = new SqlDataAdapter(query, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ddlstudent.DataSource = ds;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
//ddlstudent.Items.Insert(0, new ListItem(get_SchName.ToString(), "0"));
ddlstudent.SelectedIndex = 0;
}
else
{
ddlstudent.Items.Insert(0, "No Student");
ddlstudent.DataBind();
}
}
}
}
}
I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.
Here is the code that I used
.aspx code
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<h2>Employee Details</h2>
</td>
</tr>
<tr>
<td>ID</td>
<td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>BloodGroup</td>
<td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Emergency Contact No.</td>
<td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Photo:</td>
<td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />
<asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />
<asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'
Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Image_upload
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileuploadEmpImage.HasFile)
{
int length = fileuploadEmpImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadEmpImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
int id = Convert.ToInt32(txtID.Text);
string name = txtName.Text;
string bloodGroup = txtBloodGroup.Text;
string phoneNo = txtContactNo.Text;
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtBloodGroup.Text = string.Empty;
txtContactNo.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
BindGridData();
}
}
}
private void BindGridData()
{
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
grdEmployee.DataSource = dt;
grdEmployee.DataBind();
}
}
}
handler.ashx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Image_upload
{
public class Employeeimage_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
MySqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.
To fix your code introduce MySqlParameters:
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
var connection = new MySqlConnection(
ConfigurationManager.ConnectionString["database"]);
connection.Open();
// remove the order by and add a where with a parameter placeholder
var command = new MySqlCommand(
"select ImageI from database.employee where id = #id",
connection);
// setup parameter and add to command
command.Parameters.AddWithValue("#id", imageid);
// execute
MySqlDataReader dr = command.ExecuteReader();
// rest of your code
}
Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files
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?
I've a listview that allows Editing and Delete.
When I Click on the linkbutton in the listview, it fires up page_load then to OnItemCommand.
At the end of the command I added DataBind Which does not refresh my listview but deleted my entry.
If I change the DataBind to Redirect back to the same page with (...aspx?ID=...) it will return me a fresh new page. but in debug mode, I saw it run through page_load and the Databind.
<asp:UpdatePanel ID="UpdateOptions" runat="server" >
<ContentTemplate>
<asp:Panel ID="OPanel" runat="server" width="350px">
<asp:ListView runat="server" ID="lvPollOptions" DataKeyNames="POptionID" OnItemCommand="lvPollOptions_ItemCommand" OnDataBound="lvPollOptions_ItemDataBound" >
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="300px">
<tr class="AdminListHeader">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("OptionText")%>
</td>
<td>
<%#Eval("Votes")%>
</td>
<td align="center">
<asp:ImageButton runat="server" ID="ibtnEditOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Edit" ImageUrl="~/images/buttons/EditPencil.gif" AlternateText="Edit" CssClass="AdminImg" />
</td>
<td>
<asp:ImageButton runat="server" ID="ibtnDeleteOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Delete" ImageUrl="~/images/buttons/delete.gif" AlternateText="Delete" CssClass="AdminImg" OnClientClick="return confirm('Warning: This will delete the Poll Option from the database.');" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Label ID="lblNoOption" runat="server" Text="No Options Added"></asp:Label>
<table width="345px">
<tr>
<td width="100px">
Option:
</td>
<td>
<asp:TextBox ID="txtOption" runat="server" width="200px"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
string PID = Request.QueryString["ID"];
if (!IsPostBack)
{
if (PID == null)
{
}
else if (PID != null)
{
PollBindData();
}
}
}
protected void lvPollOptions_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string PID = Request.QueryString["ID"];
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void lvPollOptions_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string selectedID = e.CommandArgument.ToString();
SqlConnection connDeleteOption = new SqlConnection(connStr);
connDeleteOption.Open();
SqlCommand cmdDeleteOption = new SqlCommand("DELETE FROM [PollOptions] WHERE POptionID = '" + selectedID + "'", connDeleteOption);
cmdDeleteOption.ExecuteNonQuery();
connDeleteOption.Close();
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + selectedID);
}
if (e.CommandName == "Edit")
{
string EditID = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmdView = new SqlCommand("SELECT OptionText From [PollOptions] Where POptionID = '" + EditID + "'", conn);
SqlDataReader dr1 = cmdView.ExecuteReader();
if (dr1.Read())
{
txtOption.Text = dr1["OptionText"].ToString();
}
Session["OptionID"] = txtOption.Text;
dr1.Close();
conn.Close();
lbOInsert.Visible = false;
lbOUpdate.Visible = true;
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + EditID);
}
}
Before we start - your code has a security risk since it is prone to Sql Injection, make sure you Parametrize your queries...
Now, your question is not very clear, but if I understand correctly, you're saying that after you delete an object, the Listview isn't refreshed after postback (e.g. you still see the deleted item). Since you're running in an UpdatePanel, make sure to update the panel after the DataBind...
Update PoolBindData like this
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
// POTENTIAL SECURITY RISK - MAKE SURE YOU PARAMETRIZE THE QUERY!!
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataTable dsSel = new DataTable();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
// Update panel
UpdateOptions.Update();
}
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 />