how to delete using checkbox in asp repeater control with button? - c#

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");
}
}

Related

How to filter query in asp.net using dropdown list?

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();
}
}

Why isn't the UpdatePanel found to update the data

I have the following code in my ASP.net page:
<asp:UpdatePanel runat="server" ClientIDMode="Static" UpdateMode="Conditional" ID="upClickShowTask">
<ContentTemplate>
<asp:LinkButton ID="lbShowTask" CssClass="btnExport" ClientIDMode="Static" runat="server" Text="Generate Tasks" OnClick="btnFilter_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pageTab8" ClientIDMode="Static" runat="server">
<asp:Panel ID="demoCli" ClientIDMode="Static" runat="server" BorderWidth="2" BorderColor="#FF0000">
<asp:UpdatePanel ID="upGenTaskCli" runat="server" UpdateMode="Conditional" ClientIDMode="Static">
<ContentTemplate>
Client: <asp:Label ID="lblCli" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Onboarding Date: <asp:Label ID="lblCliDate" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Contact Information: <asp:Label ID="lblCliCont" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Notes: <asp:Label ID="lblCliNotes" runat="server" ClientIDMode="Static" Text=""></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</asp:Panel>
The code-behind:
protected void btnFilter_Click(object sender, EventArgs e)
{
demoCli.Visible = false;
demoSit.Visible = false;
demoPra.Visible = false;
demoPro.Visible = false;
connString = #""; //my connection string
#region queries
string queryCli = #"SELECT
C.OBJECTID
,C.ATTR2815 'Client'
,C.ATTR2881 'Onboarding Date'
,C.ATTR2880 'Contact Information'
,M.MEMO 'Notes'
FROM HSI.RMOBJECTINSTANCE1231 C INNER JOIN HSI.RMMEMO M ON C.MK2879 = M.MEMOID";
string querySit = #"SELECT
S.OBJECTID
,S.ATTR2819 'Site'
,S.FK2820 'RelatedClient'
,S.ATTR2873 'Address'
,S.ATTR2874 'City'
,S.ATTR2875 'State'
,S.ATTR2876 'Zip'
,M.MEMO 'Notes'
,S.ATTR2878 'Onboarding Date'
FROM HSI.RMOBJECTINSTANCE1229 S INNER JOIN HSI.RMMEMO M ON S.MK2877 = M.MEMOID";
string queryPra = #"SELECT
P.OBJECTID
,P.ATTR2817 'Practice'
,P.FK2818 'RelatedSite'
,P.ATTR2882 'Onboarding Date'
,M.MEMO 'Notes'
FROM HSI.RMOBJECTINSTANCE1230 P INNER JOIN HSI.RMMEMO M ON P.FK2818 = M.MEMOID";
string queryPro = #"SELECT
P.OBJECTID
,P.ATTR2919 'Provider'
,P.ATTR2920 'Start Date'
,P.FK2921 'RelatedPractice'
,P.FK2922 'RelatedClient'
FROM HSI.RMOBJECTINSTANCE1249 P";
#endregion
string query = "";
using (SqlConnection conn = new SqlConnection(connString))
{
if (ddlCli.SelectedIndex > 0)
{
try
{
demoCli.Visible = true;
query = queryCli + " WHERE C.ATTR2815 = '" + ddlCli.SelectedValue + "'";
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
lblCli.Text = myDataSet.Tables[0].Rows[0]["Client"].ToString();
lblCliDate.Text = myDataSet.Tables[0].Rows[0]["Onboarding Date"].ToString();
lblCliCont.Text = myDataSet.Tables[0].Rows[0]["Contact Information"].ToString();
lblCliNotes.Text = myDataSet.Tables[0].Rows[0]["Notes"].ToString();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
if (ddlSit.SelectedIndex > 0)
{
try
{
demoSit.Visible = true;
query = querySit + " WHERE S.ATTR2819 = '" + ddlSit.SelectedValue + "'";
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
lblSit.Text = myDataSet.Tables[0].Rows[0]["Site"].ToString();
lblSitRC.Text = myDataSet.Tables[0].Rows[0]["RelatedClient"].ToString();
lblSitAdd.Text = myDataSet.Tables[0].Rows[0]["Address"].ToString();
lblSitCity.Text = myDataSet.Tables[0].Rows[0]["City"].ToString();
lblSitSt.Text = myDataSet.Tables[0].Rows[0]["State"].ToString();
lblSitzip.Text = myDataSet.Tables[0].Rows[0]["Zip"].ToString();
lblSitOnDate.Text = myDataSet.Tables[0].Rows[0]["Onboarding Date"].ToString();
lblSitNotes.Text = myDataSet.Tables[0].Rows[0]["Notes"].ToString();
//upGenTaskCli.Update();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
if (ddlPra.SelectedIndex > 0)
{
try
{
demoPra.Visible = true;
query = queryPra + " WHERE P.ATTR2817 = '" + ddlPra.SelectedValue + "'";
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
lblPra.Text = myDataSet.Tables[0].Rows[0]["Client"].ToString();
lblPraRS.Text = myDataSet.Tables[0].Rows[0]["RelatedSite"].ToString();
lblPraOnDate.Text = myDataSet.Tables[0].Rows[0]["Onboarding Date"].ToString();
lblPraNotes.Text = myDataSet.Tables[0].Rows[0]["Notes"].ToString();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
if (ddlPro.SelectedIndex > 0)
{
try
{
demoPro.Visible = true;
query = queryPro + " WHERE P.ATTR2919 = '" + ddlPro.SelectedValue + "'";
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
lblPro.Text = myDataSet.Tables[0].Rows[0]["Provider"].ToString();
lblProStart.Text = myDataSet.Tables[0].Rows[0]["Start Date"].ToString();
lblProRP.Text = myDataSet.Tables[0].Rows[0]["RelatedPractice"].ToString();
lblProRC.Text = myDataSet.Tables[0].Rows[0]["RelatedClient"].ToString();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
upGenTaskCli.Update();
}
}
I added breakpoints for these lines:
lblCli.Text = myDataSet.Tables[0].Rows[0]["Client"].ToString();
lblCliDate.Text = myDataSet.Tables[0].Rows[0]["Onboarding Date"].ToString();
lblCliCont.Text = myDataSet.Tables[0].Rows[0]["Contact Information"].ToString();
lblCliNotes.Text = myDataSet.Tables[0].Rows[0]["Notes"].ToString();
And hovering the mouse over them, displays the text data but the upGenTaskCli is not updating to show the data.
I receive this error:
0x800a139e - Microsoft JScript runtime error: Sys.InvalidOperationException: Could not find UpdatePanel with ID 'upGenTaskCli'. If it is being updated dynamically then it must be inside another UpdatePanel.
How do I resolve the issue?
Since its a JS visibilty error, Try to put your Update Panel inside another update panel
like this:
//this is how your view should look like
<asp:UpdatePanel ID="pnlParent" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:UpdatePanel ID="upGenTaskCli" runat="server" UpdateMode="Conditional" ClientIDMode="Static">
<ContentTemplate>
Client: <asp:Label ID="lblCli" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Onboarding Date: <asp:Label ID="lblCliDate" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Contact Information: <asp:Label ID="lblCliCont" ClientIDMode="Static" runat="server" Text=""></asp:Label>
<br />
Notes: <asp:Label ID="lblCliNotes" runat="server" ClientIDMode="Static" Text=""></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</contentTemplate>
</updatePanel>
so in your code behind do the following :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager.RegisterStartupScript
(this, typeof(Page), "UpdateMsg", "$(document).ready(function(){$('#upGenTaskCli').hide();});", true);
}
}
//and then in your button Logic add the following line in the If clause :
protected void btnFilter_Click(Object sender, EventArgs e)
{
if (ddlCli.SelectedIndex > 0)
{
try
{
query = queryCli + " WHERE C.ATTR2815 = '" + ddlCli.SelectedValue + "'";
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
lblCli.Text = myDataSet.Tables[0].Rows[0]["Client"].ToString();
lblCliDate.Text = myDataSet.Tables[0].Rows[0]["Onboarding Date"].ToString();
lblCliCont.Text = myDataSet.Tables[0].Rows[0]["Contact Information"].ToString();
lblCliNotes.Text = myDataSet.Tables[0].Rows[0]["Notes"].ToString();
}
catch (Exception ex)
{
string error = ex.Message;
}
ScriptManager.RegisterClientScriptBlock
(this, typeof(System.Web.UI.Page), "MyJSFunction", "$('#upGenTaskCli').toggle();", true);
}
//it should work

button click event is not firing in a pop up window

i have a website in asp.Net which contains a pop up with a asp button. my problem is that button click event is not firing in pop up. my pop opens when imagebutton1 clicks. i am also using timer tick in that.
i am totally stucked in it.
my code is as follows:-
<div>
<script type="text/javascript">
function buttonClicked() {
var textBox = $get("TextBox1");
textBox.scrollTop = textBox.scrollHeight;
}
</script>
<asp:UpdatePanel ID="ChatUpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<div id="second1" runat="server" style="width:570px;height:100px;background-color:#e5f7f6;border:solid 2px #35b8b3;position:absolute;margin-left:5px;margin-top:5px;border-radius:5px;">
<span style="color:Blue;font-weight:bold;margin-left:180px;margin-top:20px;">Ringing Expert...Please Wait</span>
</div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" ReadOnly="True"
width="100%" style="resize:none;" Height="200px" AutoPostBack="False"
MaintainScrollPositionOnPostBack="True" >
</asp:TextBox>
</ContentTemplate>
<Triggers>
<%--<asp:AsyncPostBackTrigger ControlID="SendButton" EventName="Click" />--%>
<asp:AsyncPostBackTrigger ControlID="ChatTextTimer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer runat="server" ID="ChatTextTimer" Interval="100"
ontick="ChatTextTimer_Tick" />
<asp:TextBox ID="NewMessageTextBox" DefaultButton="SendButton" Columns="50" runat="server" Height="25px"
Width="80%" style="margin-left: 0px;margin-top:5px;" Font-Size="Medium" />
<asp:Button ID="SendButton" Text="Send" runat="server" OnClick="SendButton_Click" Height="25px" style="margin-left:50px;" />
Report Abuse
<br />
<div style="width:100%;margin-top:10px;">
<asp:Image ID="Image3" runat="server" Width="70px" Height="50px" />
<div style="width:80%;height:50px;float:right;margin-right:30px;">
Status:<br />
<span style="color:Blue;font-weight:bold;font-size:large;">Not Charging</span>
<span style="float:right;font-weight:bold;font-size:medium;color:Blue;">$ <asp:Label ID="Label12" runat="server" style="font-weight:bold;font-size:medium;color:Blue;" Text="Label"></asp:Label> / Minute</span>
</div>
</div>
and my back end code is as follows:-
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
second1.Visible = false;
if (Session["User"] != "User")
{
Response.Redirect("signin.aspx");
}
else
{
if (Int32.Parse(Label13.Text) < 20)
{
Response.Redirect("Payment.aspx");
}
else
{
if(Int32.Parse(Label14.Text)==0)
{
Response.Redirect("ExpertMail.aspx?id="+Int32.Parse(Request.QueryString["id"]));
}
else
{
string str1 = Label1.Text;
string str = "<script type='text/javascript'>$(function (){ $('#modal_dialog').dialog({title: 'Chat with Expert', modal: true }); return false; });</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", str, false);
Image3.ImageUrl = Label8.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd = new SqlCommand("Select Booked from ExpertChat where id=" + Int32.Parse(Request.QueryString["id"]), con).ExecuteReader();
rd.Read();
int y = Int32.Parse(rd["Booked"].ToString());
rd.Close();
if (y == 0)
{
SqlDataReader mRead1, mRead3,mRead4;
mRead1 = new SqlCommand("insert into chat (ExpertName,UserName,rate) Values ('" + Label1.Text + "','" + Session["SName"] + "','" + Label5.Text + "')", con).ExecuteReader();
mRead1.Close();
mRead3 = new SqlCommand("Update ExpertChat Set Booked=1 where SName='" + Label1.Text + "'", con).ExecuteReader();
mRead3.Close();
second1.Visible = true;
con.Close();
}
con.Close();
}
}
}
}
public void wait(int x)
{
}
protected void ChatTextTimer_Tick(object sender, EventArgs e)
{
if (second1.Visible)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader mRead4 = new SqlCommand("Select top 1 id from Chat where ExpertName='" + Label1.Text + "' order by id desc", con).ExecuteReader();
mRead4.Read();
int z = Int32.Parse(mRead4["id"].ToString());
mRead4.Close();
SqlDataReader rd = new SqlCommand("Select IsApproved from Chat where id=" + z, con).ExecuteReader();
rd.Read();
string str = (rd["IsApproved"].ToString());
rd.Close();
if (str == "Approved")
{
second1.Visible = false;
}
else if (str == "canceled")
{
}
else
{
con.Close();
}
}
else
{
int x1 = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd;
rd = new SqlCommand("Select UserInitial,Updated from Chat where id =" + Int32.Parse(Request.QueryString["id"].ToString()), con).ExecuteReader();
rd.Read();
string str;
int i;
str = rd["UserInitial"].ToString();
i = Int32.Parse(rd["Updated"].ToString());
rd.Close();
if (i == 1)
{
x1 = x1 + 1;
TextBox1.Text = TextBox1.Text + Environment.NewLine + str;
SqlCommand
cmd = new SqlCommand("Update Chat set Updated=0 where id=" + Int32.Parse(Request.QueryString["id"].ToString()), con);
cmd.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
con.Close();
}
}
protected void SendButton_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
//con.Open();
string messageMask = "{0} : {2}";
string message = string.Format(messageMask, Session["SName"].ToString(), DateTime.Now.ToShortTimeString(), NewMessageTextBox.Text);
TextBox1.Text = TextBox1.Text + Environment.NewLine + message;
//SqlCommand cmd, cmd1;
//cmd = new SqlCommand("Update Chat set Data='" + message + "' where id=" + Int32.Parse(Request.QueryString["id"].ToString()), con);
//cmd.ExecuteNonQuery();
//cmd1 = new SqlCommand("Update Chat set Updated1=1 where id=" + Int32.Parse(Request.QueryString["id"].ToString()), con);
//cmd1.ExecuteNonQuery();
NewMessageTextBox.Text = "";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", "document.getElementById('" + NewMessageTextBox.ClientID + "').value = '';", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
}
i have solved it .
it was a silly mistake. just set your button's SubMitBehaviour Property to false...

Binding sqldatareader to gridview c#

I am creating an application for a asp.net class that I am taking. One of the pages in the application needs to allow a user to search for a specific student via last name or user ID. When the student is found the page should display the students data and his/her class schedule.
I have gotten everything to work except for the class schedule. The approach I have taken (as we learned in class) was to get the query results via the SqlDataReader and bind it to a GridView. This is done in showStudentSchedule().
The query in this function returns the correct results when I test it against the DB I created, but the grid view displaying a students schedule doesn't show up on the page.
//StudentInformation.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="StudentInformation.aspx.cs" Inherits="StudentInformation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
<asp:Label ID="Label6" runat="server" Text="Search by Last Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</p>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:Label ID="Label5" runat="server"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Panel>
</asp:Content>
//StudentInformation.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class StudentInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userStr = TextBox1.Text;
int userInt;
bool isNum = int.TryParse(userStr, out userInt);
string sqlSelectFindUserByName;
if (isNum)
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.ID = '{0}'", userInt);
else
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.LastName LIKE '%{0}%'", userStr);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand commandFindUserByName = new SqlCommand(sqlSelectFindUserByName, connection);
connection.Open();
SqlDataReader readerFindUserByName = commandFindUserByName.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Please make a selection");
while (readerFindUserByName.Read())
DropDownList1.Items.Add(readerFindUserByName["LastName"].ToString());
if (DropDownList1.Items.Count == 2)
DropDownList1.SelectedIndex = 1;
DropDownList1_SelectedIndexChanged(null, null);
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string nameLast = DropDownList1.SelectedItem.Value;
displayStudent(nameLast);
}
private void displayStudent(String nameLast)
{
clearStudentLabel();
int userInt;
bool isNum = int.TryParse(nameLast, out userInt);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName;
sqlSelectFindUserInfoByName = string.Format("SELECT ID, FirstName, LastName, City, Phone FROM Personal_Info WHERE LastName LIKE '%{0}%'", nameLast);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
int i = 0;
while (readerFindUserInfo.Read())
{
Label1.Text = "Student ID: " + readerFindUserInfo["ID"].ToString();
Label2.Text = "First name: " + readerFindUserInfo["FirstName"].ToString();
Label3.Text = "Last name: " + readerFindUserInfo["LastName"].ToString();
Label4.Text = "City: " + readerFindUserInfo["City"].ToString();
Label5.Text = "Phone: " + readerFindUserInfo["Phone"].ToString();
}
connection.Close();
showStudentSchedule(userInt);
}
private void showStudentSchedule(int id)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName = string.Format("SELECT Class_Schedule.Section_ID, Class_Schedule.Course_ID, Class_Schedule.Days, Class_Schedule.Time, CASE WHEN Personal_Info.FirstName IS NULL THEN 'Staff' ELSE (Personal_Info.LastName + Personal_Info.FirstName) END AS Name FROM Class_Schedule JOIN Student_Enrollment ON Class_Schedule.Section_ID = Student_Enrollment.Section_ID JOIN Personal_Info ON Class_Schedule.Instructor_ID = Personal_Info.ID WHERE Student_Enrollment.Student_ID = {0}", id);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
GridView1.DataSource = readerFindUserInfo;
GridView1.DataBind();
/*
string connectionString = "Data Source=LocalHost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa_0001";
string commandString = "Select * from Customers";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(commandString);
conn.Open();
command.Connection = conn;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();
*/
}
private void clearStudentLabel()
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
Label5.Text = "";
}
}
Try this out:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand(sqlSelectFindUserByName);
connection.Open();
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();

Populating gridview based on database info when logged in session based

I'm having trouble with populating a gridview based off of logging in with a session based login. I'm using a master page. Currently I am getting a "must declare scalar variable". My thought is to retrieve it somewhere in the script area. Any help is greatly appreciated!!!!
The problem now is what the code should be for the non-master page to retrieve the specific information for someone based of their uname(column in database) or UID(primary key and ideal way)
Code for master page (relevant stuff at least)
protected void btnlogin2_Click(object sender, EventArgs e)
{
if (btnlogin2.Text == "Login")
{
string strCmd = "Select * From Person Where uname=#uname and upass=#upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.Read())
{
Session["uname"] = txtusername.Text;
if (objDR["Type"].ToString() == "Member")
{ Response.Redirect("member.aspx"); }
else if (objDR["Type"].ToString() == "Pledge")
{ Response.Redirect("member.aspx"); }
else if (objDR["Type"].ToString() == "Admin")
{ Response.Redirect("eboard.aspx"); }
}
else
{
// btnlogin2.Text = "Failed";
}
}
btnlogin2.Text = "Logout";
}
else if (btnlogin2.Text == "Logout")
{
btnlogin2.Text = "Login";
txtusername.Visible = true;
txtpassword.Visible = true;
pnlSideBar.Visible = false;
Session.Abandon();
Response.Redirect("index.aspx");
}
btnlogin2.Text = "Failed";
}
Code for page
<%# Page Language="C#" Debug="true" MasterPageFile="masterpage.master" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Web.Configuration" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string strConn = WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString;
if (User.Identity.IsAuthenticated)
{
Button btnlogin2 = (Button)Master.FindControl("btnlogin2");
TextBox txtusername = (TextBox)Master.FindControl("txtusername");
TextBox txtpassword = (TextBox)Master.FindControl("txtpassword");
Panel pnlSideBar = (Panel)Master.FindControl("pnlSideBar");
Panel pnlPledge = (Panel)Master.FindControl("pnlPledge");
Panel pnlEboard = (Panel)Master.FindControl("pnlEboard");
string strCmd = "Select * From Person Where uname=#uname";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", Session["uname"]);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.Read())
{
btnlogin2.Visible = true;
btnlogin2.Text = "Logout";
txtusername.Visible = false;
txtpassword.Visible = false;
if (objDR["Type"].ToString() == "Admin")
{
pnlEboard.Visible = true;
pnlPledge.Visible = false;
pnlSideBar.Visible = false;
}
else if (objDR["Type"].ToString() == "Member")
{
pnlEboard.Visible = false;
pnlPledge.Visible = false;
pnlSideBar.Visible = true;
}
else if (objDR["Type"].ToString() == "Pledge")
{
pnlPledge.Visible = true;
pnlEboard.Visible = false;
pnlSideBar.Visible = false;
}
lblLogin.Text = "Logged in as: " + objDR["Fname"] + " " + objDR["Lname"];
}
}
}
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphText" runat="server">
<div id="mainContent">
<h1> My Service Hours</h1>
<p> </p>
<table width="318" height="126" border="1" cellspacing="1">
<caption>
Event Event Date Hours
</caption>
<tr>
<th width="100" scope="col">Polar Plunge</th>
<th width="100" scope="col">1/13/12</th>
<th width="100" scope="col">5 hrs</th>
</tr>
</table>
<form id="form3" name="form2" method="post" action="">
<label for="Totalhrs"></label>
Total: 5hrs
</form>
<asp:GridView ID="grvServiceHours" DataSourceID="srcServiceHours" runat="server"/>
<asp:SqlDataSource
id="srcServiceHours"
ConnectionString="<%$ ConnectionStrings:cloud2 %>"
SelectCommand="select Event.Event_Name, Event.Event_Time, Event.Event_Type, Service_Hours.Hours, Service_Hours.Hours_Completed
from Event, Service_Hours, Person
where Event.EvID=Service_Hours.EvID and Person.UID=Service_Hours.UID and Person.Uname=#uname"
Runat="server" />
<p> </p>
<!-- end #mainContent --></div>
</asp:Content>
Create a propery in your master and use it any where on your content page rather than a variable. Master page property is accesible any where on the content page by adding a directive in your aspx page.

Categories

Resources