I am using 4 radiobuttons as options to a question. The question and the radiobuttons are refreshed after button click. The checked radiobutton text is compared with the answer and if it matches, a counter is increased. I have found that when I check a radiobutton first time the corresponding radiobutton on the next question will be checked already and if it is the answer it will increase the counter and if i change it to check another radiobutton which is the actual answer the counter is not increased. Do I have to specify any property for the updatepanel that i am using to refresh the question. Thnk you for time to read this long one.
This is my aspx code
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style>
.con{
width:70%;
margin:auto;
}
.testres{
display:none;
}
.btnHome{
display:none;
color:rgb(0,159,37);
text-decoration:none;
background:none;
border:1px solid grey;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="con">
<div class="subject-name">
<asp:Label runat="server" Text="Subject : " /><asp:Label ID="lblSubjectName" runat="server" Text="" />
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="question-options">
<fieldset>
<legend><asp:Label ID="lblQ" runat="server" Text="Q.No. "/><asp:Label ID="lblQuesNo" runat="server" Text="" /></legend>
<asp:Panel ID="question" runat="server">
<asp:Label ID="lblQues" runat="server" Text="" />
<ul style="list-style-type:none">
<li><asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton4" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
</ul>
</asp:Panel>
<asp:Panel ID="Panel1" CssClass="testres" runat="server">
<asp:Label ID="Label1" runat="server" Text="Correct Answers : "></asp:Label>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</asp:Panel>
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click"/>
<asp:Button ID="btnHome" runat="server" Text="Home" CssClass="btnHome" OnClick="btnHome_Click"/>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
This is code behind
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class OnlineTest_Question : System.Web.UI.MasterPage
{
SqlConnection con = new SqlConnection("Password=password#123;Persist Security Info=True;User ID=sa;Initial Catalog=MyDatabasae;Data Source=.");
SqlCommand cmd=new SqlCommand();
SqlDataReader rdr;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
DataTable dt3 = new DataTable();
static int rowcount=0;
static int totalrowcount;
string id = "";
string subname = "";
string correctans = "";
int i = 1;
static int correctcount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cmd.CommandText = "select subject from subjectstb where subid='" + Request.QueryString["sid"] + "'";
cmd.Connection = con;
con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
subname = rdr["subject"].ToString();
}
rdr.Close();
con.Close();
lblSubjectName.Text = subname;
try
{
cmd.CommandText = "select * from questionstb where subject='" + Request.QueryString["sid"] + "'";
con.Open();
cmd.Connection = con;
rdr = cmd.ExecuteReader();
dt.Load(rdr);
rdr.Close();
totalrowcount = dt.Rows.Count;
lblQues.Text = dt.Rows[0]["question"].ToString();
id = dt.Rows[0]["qid"].ToString();
cmd.CommandText = "select * from optionstb where qid='" + id + "'";
rdr = cmd.ExecuteReader();
dt1.Load(rdr);
RadioButton1.Text = dt1.Rows[0]["choice"].ToString();
RadioButton2.Text = dt1.Rows[1]["choice"].ToString();
RadioButton3.Text = dt1.Rows[2]["choice"].ToString();
RadioButton4.Text = dt1.Rows[3]["choice"].ToString();
lblQuesNo.Text = (rowcount + 1).ToString();
correctans = dt1.Rows[0]["correct"].ToString();
if (RadioButton1.Checked == true && RadioButton1.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton2.Checked == true && RadioButton2.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton3.Checked == true && RadioButton3.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton4.Checked == true && RadioButton4.Text == correctans)
{
correctcount = correctcount + 1;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if(rowcount<5)
{
if(rowcount>=totalrowcount)
{
lblQuesNo.Text = "Not Available";
lblQues.Text = "No more questions available.";
}
else
{
cmd.CommandText = "select * from questionstb where subject='" + Request.QueryString["sid"] + "'";
con.Open();
cmd.Connection = con;
rdr = cmd.ExecuteReader();
dt3.Load(rdr);
rdr.Close();
totalrowcount = dt3.Rows.Count;
lblQuesNo.Text = (rowcount+1).ToString();
lblQues.Text = dt3.Rows[rowcount]["question"].ToString();
dt1.Load(rdr);
id = dt3.Rows[rowcount]["qid"].ToString();
cmd.CommandText = "select * from optionstb where qid='" + id + "'";
rdr = cmd.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(rdr);
rdr.Close();
RadioButton1.Text = dt2.Rows[0]["choice"].ToString();
RadioButton2.Text = dt2.Rows[1]["choice"].ToString();
RadioButton3.Text = dt2.Rows[2]["choice"].ToString();
RadioButton4.Text = dt2.Rows[3]["choice"].ToString();
cmd.CommandText = "select * from optionstb where qid='"+id+"'";
rdr = cmd.ExecuteReader();
DataTable d=new DataTable();
d.Load(rdr);
correctans = d.Rows[0]["correct"].ToString();
if (RadioButton1.Checked == true && RadioButton1.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton2.Checked == true && RadioButton2.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton3.Checked == true && RadioButton3.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton4.Checked == true && RadioButton4.Text == correctans)
{
correctcount = correctcount + 1;
}
rowcount = rowcount + 1;
}
}
else
{
con.Close();
Label2.Text = correctcount.ToString();
question.Style.Add("display","none");
Panel1.Style.Add("display", "block");
btnNext.Text = "";
lblQ.Text = "Result";
btnHome.Style.Add("display", "block");
lblQuesNo.Text = "";
btnNext.Style.Add("background", "none");
btnNext.Style.Add("border", "none");
}
}
protected void btnHome_Click(object sender, EventArgs e)
{
rowcount = 0;
correctcount = 0;
Response.Redirect("testselect.aspx");
}
}
You should put the code chunk that controls this process. Otherwise we can not help you.
Related
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();
}
}
i'am new in c#. i want to show data from database look like chart then i try to use Higchart.Js but the problem is when finish a process ,it not show anything about chart.
this is out put
this is my code in View.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="fuck.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/Highcharts-3.0.1/js/highcharts.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/Main.css" rel="stylesheet" />
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</head>
<body>
<form id="Form1" class="form-inline" runat="server">
<div class="form-group">
<asp:label id="myLabel" runat="server" />
<asp:Button ID="btnLogout" CssClass="btn" runat="server" Text="Logout" OnClick="btnLogout_Click" />
</div>
<div class="container">
<div class="legend">
<h3>Create charts</h3>
</div>
<table border="0">
<tr>
<td>
<asp:ListBox ID="ListDepartmentAll" SelectionMode="Multiple" runat="server" Width="180"></asp:ListBox>
</td>
<td>
<asp:Button id="btn_add" runat="server" Text=">>" CssClass="btn" OnClick="btn_add_Click" />
<asp:Button id="btn_remove" runat="server" Text="<<" CssClass="btn" OnClick="btn_remove_Click" />
</td>
<td>
<asp:ListBox ID="ListDepartmentSelect" SelectionMode="Multiple" runat="server" Width="180"></asp:ListBox>
</td>
<td>
<asp:ListBox ID="option_plot" SelectionMode="Single" runat="server" Width="180">
<asp:ListItem Value="Per Month"></asp:ListItem>
<asp:ListItem Value="Per Quoter"></asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:Button ID="btn_plot" runat="server" Text="Plot Grap" CssClass="btn btn-success" OnClick="btn_plot_Click1" />
</td>
</tr>
</table>
</div>
<div>
<highcharts:ColumnChart runat="server" ID="hc_charts" />
</div>
</form>
</body>
</html>
And this is my controll.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Highcharts.Core;
using Highcharts.Core.Data.Chart;
namespace fuck
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=supertong-pc\sqlexpress;Initial Catalog=TestProject;Integrated Security=True");
List<String> title = new List<string>();
List<String> title_name = new List<string>();
//value if title have 1
List<Double> value_type1 = new List<double>();
List<Double> value_type2 = new List<double>();
List<Double> value_type3 = new List<double>();
List<Double> value = new List<double>();
SqlDataReader data_read;
string option;
int title_id;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
//get user name from Session
myLabel.Text = (String)Session["UserName"];
String dpm = (String)Session["DPM"];
if (Session["UserName"] == null)
{
Response.Redirect("~/test.aspx");
}
else
{
try
{
sqlCon.Open();
SqlCommand cmd = new SqlCommand("select title from titlevalue where dpm = '" + dpm + "'", sqlCon);
//use data read to read sqlcommand query
data_read = cmd.ExecuteReader();
while (data_read.Read())
{
//add title item to listbox ListDepartmentAll
ListDepartmentAll.Items.Add(Convert.ToString(data_read["title"]));
}
data_read.Close();
sqlCon.Close();
}
catch (Exception ex)
{
Response.Write("Error exception ::" + ex.Message.ToString());
}
//load title value in sql to fetch in list box
}
}
}
protected void btnLogout_Click(object sender, EventArgs e)
{
//clear session
Session.Abandon();
Response.Redirect("~/LoginForm.aspx");
}
protected void btn_add_Click(object sender, EventArgs e)
{
//add
foreach (ListItem li in ListDepartmentAll.Items)
{
if (li.Selected == true)
{
ListDepartmentSelect.Items.Add(li);
}
}
//remove
foreach (ListItem li in ListDepartmentSelect.Items)
{
ListDepartmentAll.Items.Remove(li);
}
}
protected void btn_remove_Click(object sender, EventArgs e)
{
//add
foreach (ListItem li in ListDepartmentSelect.Items)
{
if (li.Selected == true)
{
ListDepartmentAll.Items.Add(li);
}
}
//remove
foreach (ListItem li in ListDepartmentAll.Items)
{
ListDepartmentSelect.Items.Remove(li);
}
}
protected void btn_plot_Click1(object sender, EventArgs e)
{
int num = ListDepartmentSelect.Items.Count;
if (num != 0) {
//check option plot
option = Convert.ToString(option_plot.SelectedItem.ToString());
if (option == "Per Month") {
// how many item in ListdepartmentSelecte
if (num == 1) {
foreach (ListItem item in ListDepartmentSelect.Items)
{
try
{
sqlCon.Open();
SqlCommand get_titleID = new SqlCommand("select id from titlevalue where title ='" + item.Value.ToString() + "'", sqlCon);
data_read = get_titleID.ExecuteReader();
while (data_read.Read())
{
title_id = Convert.ToInt32(data_read["id"]);
}
data_read.Close();
//get value_type1
SqlCommand getValue1 = new SqlCommand("select sum(value) AS value from value where title_id ='" + title_id + "' AND cr_date >= '2005/12/01' AND cr_date <= '2006/02/28' GROUP BY MONTH(cr_date)", sqlCon);
data_read = getValue1.ExecuteReader();
while (data_read.Read())
{
value_type1.Add(Convert.ToDouble(data_read["value"]));
Response.Write(Convert.ToDouble(data_read["value"]) + "\n");
}
data_read.Close();
//get value_type2
SqlCommand getValue2 = new SqlCommand("select sum(value) AS value from value where title_id ='" + title_id + "' AND cr_date >= '2006/01/01' AND cr_date <= '2006/03/30' GROUP BY MONTH(cr_date)", sqlCon);
data_read = getValue2.ExecuteReader();
while (data_read.Read())
{
value_type2.Add(Convert.ToDouble(data_read["value"]));
Response.Write(Convert.ToDouble(data_read["value"]) + "\n");
}
data_read.Close();
//get value_type3
SqlCommand getValue3 = new SqlCommand("select sum(value) AS value from value where title_id ='" + title_id + "' AND cr_date >= '2005/01/01' AND cr_date <= '2005/03/30' GROUP BY MONTH(cr_date)", sqlCon);
data_read = getValue3.ExecuteReader();
while (data_read.Read())
{
value_type3.Add(Convert.ToDouble(data_read["value"]));
Response.Write(Convert.ToDouble(data_read["value"]) + "\n");
}
data_read.Close();
sqlCon.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
//Plot chart
hc_charts.Title = new Title("Performance Chart");
hc_charts.SubTitle = new SubTitle("Evaluate Chart");
hc_charts.XAxis.Add(new XAxisItem { categories = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } });
//set series
var test_series = new List<Serie>();
test_series.Add(new Serie { data = new object[] { 58.3, 76.2, 500, 88.2, 150.3, 60.6, 49.7, 58.9, 120.2, 80.3 }, name = "year1991", yAxis = 0 });
test_series.Add(new Serie { data = value_type1.Cast<object>().ToArray() });
test_series.Add(new Serie { data = value_type2.Cast<object>().ToArray() });
test_series.Add(new Serie { data = value_type3.Cast<object>().ToArray() });
//assign series to data source
hc_charts.DataSource = test_series;
hc_charts.DataBind();
}
}
}
}
}
}
i checked value in list it have value already .Why it not show anything .Please tell me why and how can i do. Thank you
This is error
I am having a textbox on my web form. Within this textbox I am using Jquery Auto Complete. I have taken two labels on my web form and trying to hide this label based on the condition I have given in the TextChanged event of the Textbox. But I am not able display the visible one.
This is my aspx page-
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var items=[<%=autotag %>];
$("#TextBox1").autocomplete({
source:items
});
});
</script>
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox></td>
</tr>
<tr><td colspan="2">
<asp:Panel ID="Panel1" runat="server" Visible="False">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label></asp:Panel>
</td></tr>
</table>
My cs page-
public string autotag="";
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
}
}
//This bind1() is for autocomplete.
public void bind1()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
string query="select name from tbl_data_show";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader dr=cmd.ExecuteReader();
dr.Read();
while(dr.Read())
{
if(string.IsNullOrEmpty(autotag))
{
autotag+="\""+dr["name"].ToString()+"\"";
}
else
{
autotag+=", \""+dr["name"].ToString()+"\"";
}
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
//DataTable dt1 = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Please guide me where I am doing wrong?
If am not wrong, please try by setting autopostback = true, change your asp tag line like this,
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1" AutoPostBack="True"></asp:TextBox>
Update
Try your coding in this way,
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
//Panel1.Visible = true;
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
// DataTable dt1 = new DataTable();
// SqlDataAdapter da = new SqlDataAdapter(cmd);
// da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
//if (dt1.Rows.Count > 0)
//{
// if (TextBox1.Text == dr.GetString(0))
// {
// //Label1.Text = "4";
// //Label2.Text = "5";
// Panel1.Visible=true;
// //Label1.Visible = true;
// //Label2.Visible = false;
// }
// else
// {
// //Label2.Text = "5";
// Panel1.Visible = false;
// //Label2.Visible = true;
// //Label1.Visible = false;
// }
//}
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Let me know, if you get struggle with this again.
Autocomplete Using Ajax :
Initially download ajaxcontrolkit from this link, and then add into your project using this link and then add this line into your source page (below to <%# page>)
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
aspx :
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="1"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
//bind1();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["conn"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name from tbl_data_show where " +
"name like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["name"].ToString());
}
}
conn.Close();
return customers;
}
}
}
if you are not setting Lable visibility false anywhere else, try this
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
dt = g1.return_dt("select name from tbl_data_show");
if (dt.Rows.Count > 0)
{
if (TextBox1.Text == dt.Rows[0]["name"])
{
Label1.Text = "4";
Label1.Visible = true;
}
else if (TextBox1.Text != dt.Rows[0]["name"])
{
Label2.Text = "5";
Label2.Visible = true;
}
else
{
Label1.Visible = false;
Label2.Visible = false;
}
}
}
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...
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");
}
}