Populating gridview based on database info when logged in session based - c#

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.

Related

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.

Highchart not show 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

How to hide or make it visible based on the condition given in the TextChanged event of the Textbox?

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

Binding sqldatareader to gridview c#

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

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

Categories

Resources