Highchart not show c# - c#

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

Related

Not getting correct value of textbox from findcontrol from datalist

I am trying to access values of label and textbox inside DataList Using Findcontrol. On running the program I am getting correct value of label but no value from textbox control. Here is the code
.aspx code
<asp:DataList ID="SubjectAdded" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="SubjectLbl" runat="server" Text='<%# Eval("subject") %>'</asp:Label>
</td>
<td>
<asp:TextBox ID="FeeBox" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
.aspx.cs code
for(int i=0; i<SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text ;
string str = "UPDATE table name SET FEE='" + feeTB + "' WHERE TUTOR = '" + id+ "' AND SUBJECT = '" + subjectNameLb + "'";
SqlCommand strCmd = new SqlCommand(str, con);
con.Open();
strCmd.ExecuteNonQuery();
con.Close();
}
This code works for me, maybe you missed the IsPostback?:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SubjectAdded.DataSource = new[] {
new {Id= 1, Subject = "Text 1" },
new {Id= 2, Subject = "Text 2" },
};
SubjectAdded.DataBind();
}
}
public void Page_PreRender(object sender, EventArgs e)
{
for (int i = 0; i < SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text;
Response.Write($"{subjectNameLb}: {feeTB}<br/>");
}
}

Counting the checked radiobuttons

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.

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

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

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

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