storing value into .edmx table - c#

I'm trying to store a value that is an int into a table, but I keep getting the message "cannot implicitly convert string to int" if I change the table datatype from int32 to string then I get this message http://postimg.org/image/cv1cc4jkf/full/
Can anyone help me resolve this issue? easyScoreLabel, mediumScoreLabel, and highScoreLabel are labels I dragged onto the web application from the toolbox.
protected void myScoresButton_Click(object sender, EventArgs e)
{
using (projectDBEntities1 dbcontext = new projectDBEntities1())
{
message aMessage = new message();
aMessage.userName = nameTextBox.Text;
aMessage.highScoreEasy = Int32.Parse(easyScoreLabel.Text);
aMessage.highScoreMedium = Int32.Parse(mediumScoreLabel.Text);
aMessage.highScoreHard = Int32.Parse(hardScoreLabel.Text);
dbcontext.messages.Add(aMessage);
dbcontext.SaveChanges();
}
GridView1.DataBind();
}

easyScoreLabel.Text is the string. You need to convert it to the int.
aMessage.highScoreEasy = Int.Parse(easyScoreLabel.Text);
aMessage.highScoreMedium = Int.Parse(mediumScoreLabel.Text);
aMessage.highScoreHard = Int.Parse(hardScoreLabel.Text);

Related

Error throw exception when insert data with thread

I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.

Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'

protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
List<String> pathlist = null;
if (Session["UploadedPath"] != null)
{
pathlist = (List<String>)Session["UploadedPath"];
}
else
{
pathlist = new List<string>();
}
string filename = e.FileName;
string path = "~/Documents/" + filename;
this.AjaxFileUpload1.SaveAs(Server.MapPath(path));
pathlist.Add(path);
Session["UploadedPath"] = pathlist;
}
Im getting an error like this
Unable to cast object of type System.String to type System.Collections.Generic.List1[System.String].
How can i save multiple uploaded file into the databse
Looks to me like your UploadedPath variable is a string, not a List<string> so you can't perform the following cast
pathlist = (List<String>)Session["UploadedPath"];
You will need to make sure that when you set UploadedPath it's definitely an instance of List<string> and not a string.
Are you sure 'Session["UploadedPath"];' contains a list type value ?. I think it contains a string value.
pathlist = (List<String>)Session["UploadedPath"];
will returns the above exception.
Please recheck the value your are stored in the "UploadedPath" session and make sure its a List type
Hope the below code will help you. But make sure if you save something in Session["UploadedPath"]; before, make sure it is a List type.
I am not familiar with AjaxFileUpload, if the 'e' contains only single file at a time, the below will works. But if it contains multiple files, you have to loop through it and add each file to the 'pathlist' and then save it to session
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
List<String> pathlist = new List<String>();
if (Session["UploadedPath"] != null)
{
pathlist = (List<String>)Session["UploadedPath"];
}
string filename = e.FileName;
string path = "~/Documents/" + filename;
this.AjaxFileUpload1.SaveAs(Server.MapPath(path));
pathlist.Add(path);
Session["UploadedPath"] = pathlist;
}

Get data from an object and put it in a textbox

I have an object which contains 2 pieces of information in objData[0]. The information is System_ID and Network_ID. The data is coming from a query to a database.
I want to get the data out of the object and display it in two separate text boxes, one for system_ID and one for Network_ID. Right now I am putting them into a combo box.
See below my code:
//get network ID and systenm name
private void cmbAddItem_SelectedIndexChanged(object sender, EventArgs e)
{
FASystems fSys = new FASystems(sConn);
object objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
cmbNetworkID.DataSource = objData;
cmbNetworkID.DisplayMember = "Network_ID";
cmbSysName.DataSource = objData;
cmbSysName.DisplayMember = "System_Name";
// txtNetworkID.Text = objData[0].Network_ID;
}
Assuming your C# compiler is 3.0 or up use the var keyword on the api call
var objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
Let's assume you're correct that there is an array now in objData with a type in it that has at least Network_ID as a member...
txtNetworkID.Text = objData[0].Network_ID;
should work then.
Can you post the function declaration for getSystemNetworkIDFriendlyName and show how you are populating the return type?
I recommend creating a new class to store the NetworkID and SystemID
class SystemInfo
{
public string NetworkID { get; set; }
public string SystemId { get; set; }
}
Rewrite the function getSystemNetworkIDFriendlyName to return an instance of SystemInfo. Then populating your textbox becomes:
FASystems fSys = new FASystems(sConn);
SystemInfo inf o= fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
txtNetworkID.Text = info.NetworkID;
Hope this helps,
KenC

C# Error: Cannot implicitly convert type 'int' to 'short'

I am learning C# and am using Visual Studio 2010 to build a payroll program. I get an error "Cannot implicitly convert type 'int' to 'short'".
My code is :
private void btn_add_Click(object sender, EventArgs e)
{
try
{
// Get service instance
var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>();
// Get new code
var newCode = employerPeriodService.GenerateSAPCode();
// Create object
var employerPeriodAdd =
new EmployerPeriod
{
Code = newCode,
Name = newCode,
U_Tax_year = int.Parse(cb_tax_year.Text),
//U_Day_hrs = cb_number_hours.Text,
//U_Week_days = cb_number_days_week.Text,
//U_Week_hrs = txt_number_hours_week.Text,
//U_Month_days = cb_number_days_month.Text,
//U_Month_hrs = txt_number_hours_month.Text,
//U_Fortnight_days = cb_number_days_fortnight.Text,
//U_Fortnight_hrs = txt_number_hours_fortnight.Text,
//U_Weeks_in_month = cb_avg_weeks_month.Text,
//U_No_of_Fortnights = cb_avg_fortnights_month.Text,
U_Starting_period = Convert.ToDateTime(dateTimePicker1.Text),
U_Ending_period = Convert.ToDateTime(dateTimePicker2.Text)
//U_Comments = txt_comments.Text
};
// Save record
employerPeriodService.AddEmployerPeriod(employerPeriodAdd);
MessageBox.Show("Employer Payroll Period Added Successfully. Intake Ref: " + newCode.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (RulesException ex)
{
MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
In Microsoft SQL Server where my database is, U_Tax_year is defined as smallint. What do I need to do to solve this error. Do I convert what I get from the combo box 'cb_tax_year.Text' to int and how do I achieve this.
Any help appreciated.
I suspect it's as simple as changing this:
U_Tax_year = int.Parse(cb_tax_year.Text),
to this:
U_Tax_year = short.Parse(cb_tax_year.Text),
Basically you should check the type of the U_Tax_year property and make sure you parse the text appropriately so that the result of the RHS of the = sign is assignment-compatible with the property type.
SQLServer's smallint is the equivalent of c#'s short. so try short.Parse() instead of int.Parse()
Use short.Parse rather than int.Parse

storing session id as a string and casting it back to GUID

I´m trying to use session to store a value (id). The problem is that I have to store it as a string. When trying to use the instance of the id I get the error:
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 156:
Line 157: Nemanet_Navigation newFile = new Nemanet_Navigation();
Line 158: newFile.Nav_pID = (Guid)Session["id"];
Line 159:
Line 160:
This is where I get the id and that seems to work fine. Session["id"] gets the value.
public void treeview_Navigation_SelectedNodeChanged(object sender, EventArgs e)
{
TreeNode node = treeview_Navigation.FindNode(treeview_Navigation.SelectedNode.ValuePath);
NavTreeNode nNode = node as NavTreeNode;
Session["id"]=((TreeView)sender).SelectedValue.ToString();
}
But this code does not seem to work. I get the error mentioned above.
protected void Button1_Click(object sender, EventArgs e)
{
Nemanet_Navigation newFile = new Nemanet_Navigation();
newFile.Nav_pID = (Guid)Session["id"];
}
Use Guid.Parse
protected void Button1_Click(object sender, EventArgs e)
{
Nemanet_Navigation newFile = new Nemanet_Navigation();
newFile.Nav_pID = Guid.Parse(Session["id"] as string);
}
Try using:
newFile.Nav_pID = new Guid(Session["id"].ToString());
You are converting GUID to string before saving it in session collection. But when you are retrieving it, you are trying to cast it in GUID which is invalid. String and GUID are not compatible types. Either save it as GUID or convert it into string (like you are doing) when saving and use GUID constructor that takes string to reform GUID instance.
You can do it like this:
Session["id"]=((TreeView)sender).SelectedValue.ToString();
and then retrieve it from session like:
newFile.Nav_pID = new Guid((string)Session["id"]);
By default the SessionID created by either aspx is not a GUID. You can created your own data type session id value. e.g :
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddMinutes(1.0);
myCookie.Value = g1.ToString();

Categories