Want to show a message on mouse hover on a date - asp.net

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

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

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
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.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

Object reference not set to an instance of an object while clicking on submit button

I have created a webpage in asp.net
on right hand side I have an ListBox which binds data from database when page loads, Its code at Default.aspx is as below
<asp:ListBox ID="ListOfSql" runat="server"
SelectionMode="Single" DataTextField="sql_name" DataValueField="sql_text"
style="margin-left: 0px; width:auto; height:300px" EnableViewState="true">
</asp:ListBox>
and at default.aspx.cs page its code is
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
I am calling loadSqlList() on page_load so that I can get list from database in ListBox.
Now I have an submit button
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
on default.aspx.cs page submit button's code is
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
Now when I want that on clicking on submit button then text of selected item should appear in textbox which is at left hand side
when I do so I am getting an error page
complete code of default.aspx.cs page is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
System.Data.OracleClient.OracleConnection conn = new OracleConnection("Data Source = orcl; user id=*****;password = *****; unicode = true;");
//OracleConnection conn = new OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=system;password = ravi_123;Unicode=True");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
loadSqlList();
lblLastRefresh.Text = DateTime.Now.ToShortTimeString();
lblDate.Text = DateTime.Now.ToShortDateString();
Response.Cache.SetAllowResponseInBrowserHistory(false);
//============================================= Checking user logged in or not ===================================
//if (Session["txtUserName"] == null)
//{
// Response.Write("<Script Language ='JavaScript'> alert('Session Expired, please login again')</script>");
// conn.Close();
// Response.Redirect("login.aspx");
//}
//============================================= Checking user logged in or not (END) ===================================
//=====================User Ip Tracer =======================
string UserIp = Request.ServerVariables["http_x_forwarded_for"];
string UserHost = Request.ServerVariables["http_X_forwarded_for"];
string userMacAdd = Request.ServerVariables["http_x_forwarde_for"];
if (string.IsNullOrEmpty(UserIp))
{
UserIp = Request.ServerVariables["Remote_ADDR"];
UserHost = System.Net.Dns.GetHostName();
}
LblLoc.Text = UserIp;
LblHostName.Text = UserHost;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.AddHeader("Pragma", "no-cache");
//=====================User Ip Tracer code end =======================
if (!IsPostBack)
{
}
}
protected void onclick_logout(object sender, EventArgs e)
{
conn.Close();
Session.Clear();
Response.Redirect("login.aspx");
}
protected void exportToExcel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql;
sql = txtQuery.Text.ToString();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
//================ User Details Data Insertion in DataBase Ends here ===============
da.Fill(dt);
ExportTableData(dt);
Response.Write("<Script>alert('Ip Locked in DB')</Script>");
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void btnClear_clik(object sender, EventArgs e)
{
txtQuery.Text = string.Empty;
}
private void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename="+ListOfSql.SelectedItem.Text.ToString()+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
// References for this page
// http://forums.asp.net/t/1768549.aspx
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
}
If a selection isn't made then ListOfSql.SelectedItem will be null, and therefore calling .Text on that will result in your error.
Try changing your code to something like this:
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
if(ListOfSql.SelectedItem != null)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
}

asp.net url generation

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

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