asp.net url generation - asp.net

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;
using System.Configuration;
using System.Text;
using System.Web.Services;
using System.IO;
namespace T_Smade
{
public partial class ConferenceManagement : System.Web.UI.Page
{
volatile int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
GetSessionList();
}
public void GetSessionList()
{
string secondResult = "";
string userName = "";
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
userName = HttpContext.Current.User.Identity.Name;
}
SqlConnection thisConnection = new SqlConnection(#"data Source=ZOLA-PC;AttachDbFilename=D:\2\5.Devp\my DB\ASPNETDB.MDF;Integrated Security=True");
thisConnection.Open();
SqlCommand secondCommand = thisConnection.CreateCommand();
secondCommand.CommandText = "SELECT myApp_Session.session_id FROM myApp_Session, myApp_Role_in_Session where myApp_Role_in_Session.user_name='" + userName + "' and myApp_Role_in_Session.session_id=myApp_Session.session_id";
SqlDataReader secondReader = secondCommand.ExecuteReader();
while (secondReader.Read())
{
secondResult = secondResult + secondReader["session_id"].ToString() + ";";
}
secondReader.Close();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM myApp_Session;";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString()));
string[] compare = secondResult.Split(';');
foreach (string word in compare)
{
if (word == thisReader["session_id"].ToString())
{
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
}
}
}
thisReader.Close();
thisConnection.Close();
}
catch (SqlException ex)
{
}
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = "Button_" + id + i;
b.Command += new CommandEventHandler(Button_Click);
b.CommandArgument = id;
i++;
return b;
}
private Label GetLabel(string id, string name)
{
Label tb = new Label();
tb.Text = name;
tb.ID = id;
return tb;
}
protected void Button_Click(object sender, CommandEventArgs e)
{
Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString());
}
}
when users click from this page the next page is generated as
www.mypage/Entersession.aspx?session=session_id
but i'd rather to have it like
www.mypage/Entersession.aspx?session=session_name
both session_id and session_name are from the database
any idea?
}

Just change
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
to
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));

The change you're looking for takes place in where you use your GetButton method
Change:
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
To:
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
Your first input parameter to GetButton is being mapped to the CommandArgument. So passing session_name in rather than session_id will do the trick.

Is this what you are looking for? Changing CommandArgument to name? It's a very, very easy fix.
Update
You could add a commandArgument parameter to GetButton().
private Button GetButton(string id, string name, string commandArgument)
{
Button b = new Button();
b.Text = name;
b.ID = "Button_" + id + i;
b.Command += new CommandEventHandler(Button_Click);
b.CommandArgument = commandArgument; // this changed to commandArgument
i++;
return b;
}
GetButton(thisReader["session_id"].ToString(), "Join Session", thisReader["session_name"].ToString())

Related

"Cannot implicitly convert type 'Lab06.Attendance' to 'System.Collections.Generic.List<Lab06.Attendance>" How to solve this error

AssignmentAttendance.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06 {
public partial class AssignmentAttendance : System.Web.UI.Page
{
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Attendance> attendancelist = new List<Attendance>();
attendancelist = aAttendance.getAttendanceAll();
GridView1.DataSource = attendancelist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string attributename = tb_classcode.ToString();
List<Attendance> attendanceList = new List<Attendance>();
attendanceList = aAttendance.getAttendance(attributename);
GridView1.DataSource = attendanceList;
GridView1.DataBind();
}
/* protected void edit_attendance(object sender, GridViewEditEventArgs e)
{
}*/
}
}
AssignmentContentUploadClass.cs
public class Attendance {
string _connStr =ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _ClassCode = null;
private string _Teacher_ID = "";
private string _TeachingSessions = "";
private string _Remarks = "";
public Attendance()
{
}
// Constructor that take in all data required to build a Product object
public Attendance(string ClassCode, string Teacher_ID, string TeachingSessions, string Remarks)
{
_ClassCode = ClassCode;
_Teacher_ID = Teacher_ID;
_TeachingSessions = TeachingSessions;
_Remarks = Remarks;
}
public string ClassCode
{
get { return _ClassCode; }
set { _ClassCode = value; }
}
public string Teacher_ID
{
get { return _Teacher_ID; }
set { _Teacher_ID = value; }
}
public string TeachingSessions
{
get { return _TeachingSessions; }
set { _TeachingSessions = value; }
}
public string Remarks
{
get { return _Remarks; }
set { _Remarks = value; }
}
public int createAttendance()
{
int result = 0;
string queryStr = "INSERT INTO Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks)"
+ " values (#ClassCode, #Teacher_ID, #TeachingSessions, #Remarks)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", this.ClassCode);
cmd.Parameters.AddWithValue("#Teacher_ID", this.Teacher_ID);
cmd.Parameters.AddWithValue("#TeachingSessions", this.TeachingSessions);
cmd.Parameters.AddWithValue("#Remarks", this.Remarks);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}//end Insert
public Attendance getAttendance(string ClassCode)
{
Attendance attendanceDetail = null;
string Teacher_ID, TeachingSessions, Remarks;
string queryStr = "Select * From Attendance Where ClassCode = #ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", ClassCode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
attendanceDetail = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
}
else
{
attendanceDetail = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return attendanceDetail;
}
public List<Attendance> getAttendanceAll()
{
List<Attendance> attendancelist = new List<Attendance>();
string ClassCode, Teacher_ID, TeachingSessions, Remarks;
string queryStr = "SELECT * FROM Attendance Order By ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ClassCode = dr["ClassCode"].ToString();
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
Attendance a = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
attendancelist.Add(a);
}
conn.Close();
dr.Close();
dr.Dispose();
return attendancelist;
}
}
I am not sure of the error and thus I am not able to provide much
I am trying use the getAttendance(ClassCode) function to retrieve the data based off my input of my classcode in the textbox of my AssignmentAttendance.aspx.
I am thinking of using the getAttendance function in my AssignmentAttendance.aspx file by passing in the data of my classcode entry from the textbox to retrieve the details of the Attendance based off classcode.
However, I am not too sure how that works and might need some help
My database has:
ClassCode
Teacher_ID
TeachingSessions
Remarks
If anything is missing or I did not make things clear do let me know
-Edit-
I am getting an error from my AssignmentAttendance.aspx.cs file
attendanceList = aAttendance.getAttendance(attributename);

Want to show a message on mouse hover on a date

I have used the following .net code. Which shows the holiday date which I store in database.
But i want to show some message when I hover the mouse on the date.
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;
public partial class _Default : System.Web.UI.Page
{
string connection = #"server=TOPHAN-PC; Database=Tophan;uid=sa;pwd=123";
SqlConnection con = null;
protected DataSet dsHolidays;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con = new SqlConnection(connection);
Calendar1.VisibleDate = DateTime.Today;
FillHolidayDataset();
}
}
protected void FillHolidayDataset()
{
DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year, Calendar1.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsHolidays = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (Calendar1.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = Calendar1.VisibleDate.Year + 1;
}
else
{
monthNumber = Calendar1.VisibleDate.Month + 1;
yearNumber = Calendar1.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
try
{
//ConnectionStringSettings cs;
//cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
//String connString = cs.ConnectionString;
//SqlConnection dbConnection = new SqlConnection(connString);
String query = "SELECT CDate FROM calender WHERE CDate >= #firstDate AND CDate < #lastDate";
con.Open();
SqlCommand dbCommand = new SqlCommand(query, con);
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
sqlDataAdapter.Fill(dsMonth);
}
catch
{ }
return dsMonth;
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillHolidayDataset();
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
try
{
DateTime nextDate;
if (dsHolidays != null)
{
foreach (DataRow dr in dsHolidays.Tables[0].Rows)
{
nextDate = (DateTime)dr["CDate"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
catch
{ }
}
}
By using this code,I find out that it highlighted the date with the color but I want some message when I move the mouse on the Date.
you can do it by this:
$(document).ready(function()
{
$("#holiday").hover(function () {
//Show whatever message on hover in
},
function () {
//Show whatever message on hover out
}
); });

Repeated in ASP.NET

The following code displays only the last record from the database. How to display all records?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=softmail;" + "UID=root;" + "PASSWORD=********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select name, email, website, comments from awm_comments", MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
ArrayList values = new ArrayList();
values.Add(new PositionData(a, b, c, d));
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}
}
}
public class PositionData
{
private string name;
private string ticker;
private string val3;
private string val4;
public PositionData(string name, string ticker, string val3, string val4)
{
this.name = name;
this.ticker = ticker;
this.val3 = val3;
this.val4 = val4;
}
public string Name
{
get
{
return name;
}
}
public string Ticker
{
get
{
return ticker;
}
}
public string Val3
{
get
{
return val3;
}
}
public string Val4
{
get
{
return val4;
}
}
}
}
At the moment you are creating a new ArrayList for each record; then, you're binding that new list to the repeater and overwriting the previous binding.
Instead, you need to add all your values to your list and only bind it once you've read all of your data - move your variable declaration before your loop and your DataBind invocation after your loop, like so:
ArrayList values = new ArrayList();
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
You are constantly resetting the values for that repeater.
What you should do is first collect all records into a single ArrayList and only when that is done execute a single DataBind();
Something like:
if (!IsPostBack)
{
ArrayList values = new ArrayList();
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}

Insert into table from two listbox controls

I have a requirement to insert user_id and quiz_iz into a table column, I have the below code which works for inserting multiple selected values from one control into a table column, but I cannot figure out how to insert in 2 fields from values listed on both controls when hitting Submit,.
I am using odbc connection to mysql, thats were the table i need to insert is located....
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;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertRecords(StringCollection sc, StringCollection sc2)
{
string ConnectionString = #"driver={MySQL ODBC 5.1 Driver};server=localhost;database=db_mydb;uid=;pwd=;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
StringBuilder sb = new StringBuilder(string.Empty);
StringBuilder sb2 = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO jos_jquarks_users_quizzes (quiz_id,user_id) VALUES";
sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
sb2.AppendFormat("{0}('{1}'); ", sqlStatement, item);
}
try
{
conn.Open();
OdbcCommand cmd = new OdbcCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
StringCollection sc2 = new StringCollection();
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected)
{
sc2.Add(item.Text);
}
}
InsertRecords(sc , sc2);
}
}
You should use nested foreach maybe.
foreach (string item in sc)
{
foreach (string item in sc2)
{
insert sc and sc2
}
}

System.FormatException: Input string was not in a correct format

In the following code, when I try to add an Item to an ASP DropDownList, System.FormatException: Input string was not in a correct format, is thrown.
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 ScheduleExam : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String connection = System.Configuration.ConfigurationManager.ConnectionStrings["TYCConnection"].ConnectionString;
String branch = Request.Form["ctl00$ctl00$MainContent$AdminMainContent$BranchDropDownList"];
if (!String.IsNullOrWhiteSpace(branch))
{
if (!branch.Equals("00"))
{
SqlConnection sqlConn = new SqlConnection(connection);
String semQuery = "select totalSem from branchTable where branchId='" + branch + "'";
SqlCommand semCommand = new SqlCommand(semQuery, sqlConn);
sqlConn.Open();
SqlDataReader semReader = semCommand.ExecuteReader();
semReader.Read();
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = true;
//ListItem list = new ListItem("Select");
SemesterDropDownList.Items.Add(new ListItem("select"));
for (int sem = 1; sem <= totalSem; sem++)
{
//SemesterDropDownList.Items.Add(sem.ToString());
}
sqlConn.Close();
}
else
{
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
else
{
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
protected void RegisterButton_Click(object sender, EventArgs e)
{
}
}
However, when I comment all such lines there is no exception thrown.
What could be the problem and its possible solution?
Instead of
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
try
int totalSem;
Int32.TryParse(semReader["totalSem"].ToString(),totalSem);
and if that takes care of the exception then look into addressing the issues with that field.

Resources