Class code:
using System.Data.SqlClient;
namespace WebApplication5
{
public class Class1
{
public int ID;
public string nem;
public int salar;
public void ReadIMP(int id )
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=emp;Integrated Security=True");
string Query = "select * from employee where Id = '" + id + "' ";
SqlCommand cmd = new SqlCommand(Query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ID = (int)reader["Id"];
nem = (string)reader["name"];
salar = (int)reader["salary"];
}
reader.Close();
conn.Close();
}
}
}
aspx.cs code:
protected void Read_IMP(object sender, EventArgs e)
{
try
{
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
}
catch (Exception ex)
{
LabelEX.Text = ex.Message;
}
}
aspx code:
<div>
enter the id of employees :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Id of employees is
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
name of employees is
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
salary of employee is :
<asp:Label ID="Label3" runat="server"></asp:Label>
<asp:Button ID="Button4" runat="server" Text="Search" OnClick="Read_IMP" />
<br />
<asp:Label ID="LabelEX" runat="server" Text="Label"></asp:Label>
.............................................................................
I'am using method in class to retrieve data from database and calling the method in aspx.cs page
I want to filling these attributes: ID , nem , salar into Label1 , Label2 ,Label3 haw can i do it
From your code, you already fill data in fields, let those data fill on your aspx control directly
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
Label1.Text = (string)class1.ID;
Label2.Text = class1.nem;
Label3.Text = (string)class1.salar;
i am using sql query to fetch the data from one dropdown list and want to change the second dropdown list by filter data i mean i am selecting the 1st dropdown list and the 2nd drop downlist show all the customer but i want the specific customer by cardcode when i select cardcode.
kindly help, thanks in advance
here is my 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 System.Data;
using System.Data.SqlClient;
namespace StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
name2 = CardCode.Rows[i]["CntctPrsn"].ToString();
DropDownList2.Items.Add(new ListItem(name2, name2));
}
}
//adapter.Fill(CardCode);
//DropDownList1.DataValueField = "CardCode";
//DropDownList1.DataTextField = "CardCode";
//DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
this.DropDownList2.Text = theReader["CntctPrsn"].ToString();
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
// this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
// protected void Button1_Click(object sender, EventArgs e)
// {
// SqlConnection connection = new SqlConnection();
// connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDataBaseConnectionString2"].ConnectionString;
// connection.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.CommandText = "select * from OOPR";
// cmd.Connection = connection;
// SqlDataAdapter da = new SqlDataAdapter();
// da.SelectCommand = cmd;
// DataSet ds = new DataSet();
// da.Fill(ds, " OOPR");
// SqlCommandBuilder cb = new SqlCommandBuilder(da);
// DataRow drow = ds.Tables["OOPR"].NewRow();
// drow["CardCode"] = TextBox1.Text;
// drow["CardName"] = TextBox2.Text;
// drow["OpprId"] = TextBox3.Text;
// drow["CprCode"] = TextBox4.Text;
// drow["MaxSumLoc"] = TextBox5.Text;
// ds.Tables["OOPR"].Rows.Add(drow);
// da.Update(ds, " OOPR ");
// string script = #"<script language=""javascript"">
// alert('Information have been Saved Successfully.......!!!!!.');
// </script>;";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
// }
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// connection.Open();
SqlCommand insert = new SqlCommand("Insert into OOPR(CardCode, CardName, OpprId, CprCode,MaxSumLoc) values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5 )", connection); //('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.Text + "','" + TextBox4.Text + "')", connection);
insert.Parameters.AddWithValue("#TextBox1", TextBox1.Text);
insert.Parameters.AddWithValue("#TextBox2", TextBox2.Text);
insert.Parameters.AddWithValue("#TextBox3", TextBox3.Text);
insert.Parameters.AddWithValue("#TextBox4", TextBox4.Text);
insert.Parameters.AddWithValue("#TextBox5", TextBox4.Text);
connection.Open();
// connection.CommandType=CommandType.Text;
// connection.commandType=CommandType.Text;
// try
// {
insert.ExecuteNonQuery();
connection.Close();
// }
//catch
//{
// TextBox5.Text = "Error when saving on database";
// connection.Close();
//}
//TextBox1.Text="";
//TextBox2.Text = "";
//TextBox3.Text = "";
//TextBox4.Text="";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
// this.close();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
and here is the apsx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Opportunity No. :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Total Amount Invoiced:
<asp:TextBox ID="TextBox5" runat="server" Width="193px" ></asp:TextBox>
</p>
<p>
Business partner Territory:
<asp:TextBox ID="TextBox6" runat="server" Width="174px" ></asp:TextBox>
</p>
<p>
Sales Employee:
<asp:TextBox ID="TextBox7" runat="server" Width="235px" ></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add"
Width="140px" />
<asp:Button ID="Button2" runat="server" Text="Cancel" Width="149px"
onclick="Button2_Click" />
</p>
</asp:Content>
Put your filtered customer into a DataTable(dt) and fill like this:
DropDownList2.DataTextField = "CustomerName";
DropDownList2.DataValueField = "CustomerID";
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
The list2 will change its value once the list1 trigger the selectedindexchanged event.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
//*******HERE*****//
DropDownList2.DataSource = CardCode;
DropDownList2.DataBind();
DropDownList2.DataValueField = "CardCode";
DropDownList2.DataTextField = "CntctPrsn";
//*******HERE*****//
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
//*******AND HERE*****//
this.DropDownList2.SelectedValue = selected;
//*******AND HERE*****//
}
connection.Close();
}
}
hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)
I am trying to get two text boxes to populate when a drop down list has it's value selected (and I want the data in the text boxes to change when the selection is changed without the page reloading), I wrote some code compiling what I have gathered from other questions like this, but for some reason its just not working here is my CS.
public partial class UsersFormPage : Page
{
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
FillBoxes(userddlistedit.SelectedValue);
}
private void FillBoxes(string HR_ID)
{
// Create a new dataset object
DataSet dt = new DataSet();
// Create SqlConnection
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=SQL2008R2SRV;Initial Catalog=employeetrainingtracking;Integrated Security=True";
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// Set the connection on the sql command object
cmd.Connection = conn;
cmd.CommandText = "select * from users where HR_ID='" + HR_ID + "'";
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(dt);
}
}
}
if (dt.Tables[0].Rows.Count > 0)
{
usernameedit.Text = dt.Tables[0].Rows[0]["Username"].ToString(); //Where column name us the Fields for your Table that you wanted to display in the TextBoxes
passwordedit.Text = dt.Tables[0].Rows[0]["Password"].ToString();
}
}
}
And here is the part of my page it affects:
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" DataSourceID="personnelsql" DataTextField="HR_ID" DataValueField="HR_ID" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged" />
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server" AutoPostBack="True" />
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server" AutoPostBack="True" />
</li>
I cannot seem to figure out why its not working.
This is the data source for my drop down list:
<asp:SqlDataSource ID="personnelsql" runat="server"
ConnectionString="<%$ ConnectionStrings:employeetrainingtrackingConnectionString %>"
SelectCommand="SELECT * FROM personnel ORDER BY HR_ID">
</asp:SqlDataSource>
I figured out what I was missing, so I am posting the code below so people can use it:
Here is the code that goes on the CS page:
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM users ";
selectSQL += "WHERE HR_ID='" + userddlistedit.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
usernameedit.Text = reader["Username"].ToString();
passwordedit.Text = reader["Password"].ToString();
accessleveledit.SelectedValue = reader["AccessLevel"].ToString();
reader.Close();
lblResults.Text = "";
}
finally
{
con.Close();
}
}
This is the code in the actual aspx page, I added two things:
-I added the DropDownExtender
-I added the triggers (after the but before the tag
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged"></asp:DropDownList>
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server"></asp:TextBox>
<asp:DropDownExtender ID="ExtenderUserEdit" DropDownControlID="userddlistedit" Enabled="true" TargetControlID="usernameedit" runat="server"></asp:DropDownExtender>
<asp:RequiredFieldValidator runat="server" ID="ValidateUsernameEdit" ControlToValidate="usernameedit" ErrorMessage="Username is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="ValidatePasswordEdit" ControlToValidate="passwordedit" ErrorMessage="Password is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
.....
<Triggers>
<asp:AsyncPostBackTrigger ControlID="userddlistedit" EventName="SelectedIndexChanged" />
</Triggers>
I also changed the way I got my data for the drop down list to the following (added in the CS page):
private void UsersListDD()
{
userddlist.Items.Clear();
userddlistedit.Items.Clear();
userddlistdelete.Items.Clear();
string selectSQL = "SELECT * FROM personnel";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["FirstName"] + " " + reader["LastName"];
newItem.Value = reader["HR_ID"].ToString();
userddlist.Items.Add(newItem);
userddlistedit.Items.Add(newItem);
userddlistdelete.Items.Add(newItem);
}
reader.Close();
}
finally
{
con.Close();
}
}
Hopefully, this helps someone.
hi can some one help me please. My objective is to allow users to delete multiple rows in the data base called 'messages'.
By selecting the checkboxes user will be able to delete multiple rows after pressing the button.
However nothing happen when i use the codes below. Can some one help me see if there is anything wrong with my codes? Thanks =)
source code
<%# Page Title="" Language="C#" MasterPageFile="~/MainMasterPage.master" AutoEventWireup="true" CodeFile="Messages.aspx.cs" Inherits="Messages" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<SCRIPT runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
String userLog = Session["loginuser"].ToString();
if (!IsPostBack)
{
LoadData();
}
}
public void LoadData()
{
String userLog = Session["loginuser"].ToString();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Messages WHERE receiver = '" + userLog + "'",
"server=19-20\\sqlexpress;database=mpsip;Integrated Security=SSPI");
DataTable table = new DataTable();
adapter.Fill(table);
Repeater1.DataSource = table;
Repeater1.DataBind();
PagedDataSource pds = new PagedDataSource();
pds.DataSource = table.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;
int currentPage;
if (Request.QueryString["page"] != null)
{
currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
currentPage = 1;
}
pds.CurrentPageIndex = currentPage - 1;
Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
if (!pds.IsFirstPage)
{
linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}
if (!pds.IsLastPage)
{
linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}
Repeater1.DataSource = pds;
Repeater1.DataBind();
}
<asp:Repeater ID="Repeater1" runat="server">
<itemtemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<b><%# DataBinder.Eval(Container.DataItem, "title") %></b>
<br>From UserID: <%# DataBinder.Eval(Container.DataItem,
"mlogin", "{0:d}") %>
<br />
Date: <%# DataBinder.Eval(Container.DataItem,
"dateandtime", "{0:d}") %>
<br />
MessageID: <%# DataBinder.Eval(Container.DataItem,
"messageID", "{0:d}") %>
<br />
</itemtemplate>
<separatortemplate>
<hr>
</separatortemplate>
</asp:Repeater>
<br />
<asp:HyperLink ID="linkPrev" runat="server">Previous Page</asp:HyperLink>
<asp:HyperLink ID="linkNext" runat="server">Next Page</asp:HyperLink>
<br />
<asp:Button ID="Button7" runat="server" onclick="Button7_Click"
Text="Button" />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Compose Message" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Sent Messages" />
</div>
protected void Button7_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
{
conn.Open();
SqlCommand cmdDel = conn.CreateCommand();
SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
cmdDel.Connection = conn;
cmdDel.Transaction = transaction;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
//This assumes data type of messageID is integer, change (int) to the right type
cmdDel.CommandText = "delete from messages where messageID = '" + ((String)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
cmdDel.ExecuteNonQuery();
// Continue your code here
}
transaction.Commit();
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception ex1)
{
//TODO: write log
}
}
}
}
}
There's something wrong with your code, at this line:
mysql = "delete from messages where messageID = '" + CheckBox1.Checked + "'";
It should be:
mysql = "delete from messages where messageID = '" + ((YourClass)Repeater1.Items[i].DataItem).messageID + "'";
And you should use SqlParameter instead of concatenating the String.
Besides, SqlCommand was not executed, you should add this line:
cmdDel.ExecuteNonQuery();
And you must reload data after deleting message.
Besides, you should initialize SqlConnection Object out of the for loop, and use SqlTransaction to manage the transaction.
using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
{
conn.Open();
SqlCommand cmdDel = conn.CreateCommand();
SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
cmdDel.Connection = conn;
cmdDel.Transaction = transaction;
try {
for (int i = 0; i < Repeater1.Items.Count; i++)
{
//This assumes data type of messageID is integer, change (int) to the right type
cmdDel.CommandText = "delete from messages where messageID = '" + ((int)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
cmdDel.ExecuteNonQuery();
// Continue your code here
}
transaction.Commit();
//TODO: reload data here and binding to Repeater
}
catch(Exception ex) {
try {
transaction.Rollback();
}
catch(Exception ex1) {
//TODO: write log
}
}
}
protected void Button7_Click(object sender, EventArgs e)
{
bool BindNeeded = false;
SqlConnection connDelete = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI");
connDelete.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("litMessageId");
string messageId = litMessageId.Text;
mySQL = string.Format("delete from messages where messageID = '{0}'", messageId);
SqlCommand cmdDelete = new SqlCommand(mySQL, connDelete);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
if (BindNeeded)
{
Repeater1.DataBind();
}
else
{
Response.Redirect("Messages.aspx");
}
}
catch
{
Response.Redirect("Messages.aspx");
}
}