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

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.

Related

Search bar by using LinQ

I want to show the results only that match the user input, but this code will show the whole table, do you know what is the problem? For example, if the user enters "233442" id it will only show him the users that their id "233442". The user could search by id, name, or username.
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.Configuration;
using System.Data.SqlClient;
namespace SearchBarLinQ
{
public partial class SearchBarLinQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
DataClasses1DataContext db = new DataClasses1DataContext();
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData();
}
void LoadData()
{
var st = from s in db.SearchTable2s select s;
GridView1.DataSource = st;
GridView1.DataBind();
}
}
}
Function btnsearch_Click is processing the search, but the value you found is not displayed. You need to assign the value found to the data source of girdview.
Refer to the sample code(Customize the param object of the LoadData function to be compatible with the view):
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData(st);
}
void LoadData(object param)
{
GridView1.DataSource = param;
GridView1.DataBind();
}

I want to write ASP.NET code showing the use of FileUpload

I have written a code in which when the user clicks upload button the word file should be saved and redirect to the 2nd page, the word file is saving in the given path, but it is not printing any output(it is showing me blank page)
1st page.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class pg_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string fname = FileUpload1.FileName;
if (FileUpload1.HasFiles)
{
Label1.Text = "Selected file uploaded";
}
else {
Label1.Text += "Select a file";
return;
}
int flength=FileUpload1.PostedFile.ContentLength;
Int32 a = flength * 1024;
if (flength > a)
{
Label1.Text += "File Out Of Range";
}
if (FileUpload1.PostedFile.ContentType != "application/msword")
{
Label1.Text += "Upload word files only";
}
FileUpload1.SaveAs(Server.MapPath("~")+"/Myfolder/"+
FileUpload1.FileName);
Response.Redirect("pg_viewUploads.aspx");
}
}
My 2nd page.aspx
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class pg_viewUploads : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fpath=Server.MapPath("~")+"/Myfolder";
string [] files=Directory.GetFiles(fpath);
string[] name=new string[files.Length];
FileInfo fi;
int i=0;
foreach (string s in files)
{
fi = new FileInfo(s);
name[i] = "/Myfolder/" + fi.Name;
i++;
}
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
i = 0;
sb.Append("<tr>");
for (int j = 1; j < 3; j++)
{
sb.Append("<tr>");
for (int k = 1; k <3; k++)
{
if (i > files.Length-1)
{ return; }
sb.Append("" +name[i]+"");
i++;
}
sb.Append("</tr>");
}
sb.Append("</tr>");
sb.Append("</table>");
Label b = new Label();
b.Text = sb.ToString();
b.Visible = true;
PlaceHolder1.Controls.Add(b);
}
}
This pic will give you detail idea of how to code should run
Please provide solution.any help will be appreciated, thanks in advance
The first issue I see is that you are embedding <tr> tags in a <tr> tag. This is not allowed in HTML.
The second issue I see is that you are looping over j and k for no obvious reason. Looping over the files array should be enough.

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

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

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

Resources