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
Related
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 making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
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...
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();
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");
}
}