I am working on a project in which I have a form through which I can edit a question available in a list view. Whenever I select a row from the list view and click on the 'modify' button, the text boxes above the list view load the question and its options.
This means that when I select a row in the list view and click on the 'modify' button, the question loads itself into the text boxes. I edit the question there and click on 'save' to save changes, but I am not able to access the data in the text boxes. It says {"Input string was not in a correct format."}.
My code of the form frmFormWizard's 'edit' button is given below:
frmFormWizard.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace SurveyBuilder
{
public partial class frmFormWizard : Form
{
int intPanelNumber = 1;
Boolean blnCancel = false;
//int intFlag = 1;
public frmFormWizard()
{
InitializeComponent();
}
...
private void btnEditTwoOrMoreOptions_Click(object sender, EventArgs e)
{
int QuestionID;
string sql;
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
{
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
sql = "";
sql += "SELECT * FROM SurveyQuestionLog WHERE SurveyQuestionLog.QuestionLogID = "+ QuestionID +"";
//sql += "SELECT * FROM SurveyQuestionLog";
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtTwoOrMoreQuestions.Text = (string)sdr["Question"];
txtOption1.Text = (string)sdr["Choice1"];
...
}
sdr.Close();
rs = null;
cn.Close();
}
}
Whenever I try to compile the code it says "{"Input string was not in a correct format."}" and this error is shown on the following line:
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
Please let me know what I am doing wrong.
It looks like some space include in the text.
Use
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString().Trim()
and convert to int32.
hope this code will solve you
From comments
if your ListView is in report mode (i.e. it looks like a grid) then you will need the SubItems property. lvTwoOrMoreOptions.SelectedItems gets you each items in the list view - SubItems gets you the columns. So lvTwoOrMoreOptions.SelectedItems[0].SubItems[0] is the first column value,
Please change your code like below.
int QuestionID;
bool IsIntValue = Int32.TryParse("YOUR-VARIABLE", out QuestionID);
if (IsIntValue)
{
// YOUR CODE HERE
}
Hope i will be help.
whenever i try to compile the code it says "{"Input string was not in a correct format."}"
This error won't come on compiling.
Now the error comese because you are trying to parse an invalid string to integer. To do it in a safe manner, you should do it like this
int questionID;
if(int.TryParse(vTwoOrMoreOptions.SelectedItems[0].Text.ToString(),out questionID))
{
//success code
}
else
{
//failure code
}
You might be trying to access a control inside a control, maybe a GridView or DetailsView.
Try using something like this:
empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
It looks that whatever that text is containing some characters which cannot be converted to integer like space, letters, special characters etc. Check what is coming through dropdown as below
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString();
and see if that is the case.
Related
I am try to retrieve the data from my table which I created on my SSMS. I created a list box in a form of visual studio, and I try to display the data from database, but it doesn't send anything when I try to load up the program. The database is seems to look good. That problem appear when I try to retrieve the movie_id and movie_title.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataBase
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
public void LoadData()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;"+
"Initial Catalog=online_tv;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("SELECT movie.* FROM movie", conn);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
conn.Open();
sa.Fill(dt);
conn.Close();
sa.Dispose();
cmd.Dispose();
conn.Dispose();
}
public class MyMovie
{
public int id;
public string title;
public override string ToString()
{
return title;
}
}
public void ShowMovies()
{
int i;
for (i = 0; i < dt.Rows.Count; i++)
{
MyMovie movie = new MyMovie();
movie.id = Convert.ToInt32(dt.Rows[i]["movie_id"]);
movie.title = Convert.ToString(dt.Rows[i]["movie_title"]);
listBox1.Items.Add(movie);
}
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
LoadData();
ShowMovies();
}
There are a bucketload of optimizations to be made here, but I'd like to post an answer that introduces a small but fundamental change that will make your life significantly easier. Nearly every single line of code you've written there, you can get Visual Studio to write for you; just like you get it to write code when you lay out a Form, you can have it do all of this data access stuff too, and if you've managed to get SSMS connected, then getting VS connected is virtually the same process and will mean it just works:
Add a DataSet type of file to your project, and open it
Right click on it and choose add a TableAdapter - this is like a DataAdapter on steroids
Add a new conenction - the dialog is virtually the same as SSMS so you should be able to connect your DB without any hassle
Say you want to write "a query that returns rows" - put SELECT * FROM movie in
Finish the wizard
Right click the "Fill" line in the tableadapter and choose Preview Data, hit the button and see your data. If you see no data, you connected to a database that is devoid of data
Go to your form, open the Data Sources window (View menu.. Other Windows)
Drag the movie node out of the Data Sources window and onto the form
Run the app
You'll see your data
Now that you've scratched the surface of this, you can start playing with other stuff. Throw the DataTable dt away; you won't need it. Your form has a dataset object on it, that contains a Movie property that is a MovieDataTable - a subclass of datatable that you can access in a more logical and modern manner than via "string column names" - you say, for example, yourdatasetnamehere.Movies[0].movie_title and it's already a string (time to swap your column names to PascalCase by the way) rather than somedatatable.Rows[0]["movie_title"].ToString()
To show your movies in a listbox,
add a listbox to the form
set the DataSource property to be the movieBindingSource
Set the DisplayMember to be movie_title
(All this is done visually on the forms designer, not in code)
You can consider throwing the Movie POCO away too; a MovieDataRow is created by the dataset generator; it has all the properties of your movie, in a strongly typed fashion, just like your POCO does. The tableadapter downloads the DB data and turns it into strongly typed MovieDataRow objects for you, meaning you can throw all the POCO mapping stuff in ShowMovies away too, and finally, databinding your listbox means you can toss out the bit where you build its items collection manually.
First of all, if I click a button the method cbBefüllen will execute.
private void btnEntfernen_Click(object sender, EventArgs e)
{
FeiertageEntfernen entfernen = new FeiertageEntfernen();
entfernen.cbBefüllen();
entfernen.Show();
entfernen.Focus();
}
The following method is just here as an interface between my form and a class. (Please don't ask, in my code I have some good reasons for it ;) ).
public void cbBefüllen()
{
database.cbFeiertagebefüllen();
}
The method cbFeiertagebefüllen (tries to) fills my ComboBox, which is located in the form "feiertagentfernen".
public void cbFeiertagebefüllen()
{
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
But after this whole process my ComboBox is still empty. The reader in the last picture picks the correct value from the database, but somehow it won't write it into the ComboBox.
Your problem is in this line:
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
in your cbFeiertagebefüllen()
You make a new form but you want your combo box from the form from the 1st piece of code to be filled. To fix this you could pass along an instance of the form to the filling method.
The updated 2 pieces of code will be (first piece can be left alone):
In cbBefullen:
database.cbFeiertagebefüllen(this);
//'this' means we're passing along the form as parameter
In cbFeiertagebefüllen:
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
The FeiertageEntfernen form instance on which you're filling the cbFeiertag combo box in cbFeiertagebefüllen() is not the form's instance you're showing after that. You need to pass the entfernen instance to cbFeiertagebefüllen():
public void cbBefüllen()
{
database.cbFeiertagebefüllen(this);
}
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
// Use the passed in instance instead of a newly created one
//FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
// ....................
}
For this to work, the ComboBox which you need to fill, should be globally declared, i.e. outside the scope of your functions. The rest is probably fine. Also it's better if you get the values you need to display in the comboBox to the main form rather than calling the ComboBox instance 2 levels deeper.
I know this is a little confusing, in simple words, What you could do is, fill the values(descriptions of the holidays) from the DataBase into a list. Make your functions return this list when called. And finally where the ComboBox is declared, you could just add that list as the source of the ComboBox
It looks like you are adding the options to the combo box, but you are not actually setting the selected item.
To do so, you need to set cbFeiertag.SelectedIndex or cbFeiertag.SelectedValue.
I have a bit of a weird problem here. I'm attempting to create a form that, when making a selection from a ListBox, will poll data from a database and display it in a RichTextBox. I need the data to be in RTF for formatting purposes.
It works fine if I do something like this:
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
//CallDescriptionTest();
CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest2()
{
switch (DescriptionName)
{
case "Test":
DescriptionText = #"{\rtf1\ansi\ Test}";
break;
case "Words":
DescriptionText = #"{\rtf1\ansi\ A really long phrase}";
break;
}
}
In such a case, the RichTextBox (SaveRichTest) will take the data and display it just fine.
However, if I do something like this, where the Description column in the database has the text entered exactly as above (ex - #"{\rtf1\ansi\ Test}"):
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
CallDescriptionTest();
//CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest()
{
using (SqlConnection con = new SqlConnection(BuildDB))
{
con.Open();
string sql = String.Format("Select * from Abilities where Name = '{0}'", DescriptionName);
SqlCommand oCmd = new SqlCommand(sql, con);
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
DescriptionText = Convert.ToString(oReader["Description"]);
}
con.Close();
}
}
}
This will instead cause the program to crash, with an error that the "File format is not valid".
I know the text is pulling from the database correctly, because if I change "SaveRichTest.Rtf" to "SaveRichTest.Text", it displays it properly (albeit with the RTF formatting code displayed).
I just can't figure out why it won't take the string properly in the second case. It makes no sense to me whatsoever. Can someone help?
I guess in the case when you tried to show your output in plain text your output was: #"{\rtf1\ansi\ Test}
This would mean when you want to show this string formatted directly from the database you would pass it "#"{\rtf1\ansi\ Test}"" instead of the correct format. I'd suggest you store the format without the # in the database and simply show the result.
I am saving a checkbox value using 'Yes' & 'No' and my problem is I have a button click that would allow the user to change the value.
So my logic is, if button is clicked the checkbox value that is no would change to yes.
Here is what I have to save the information originally:
public void StoredProcedure()
{
string privateItem = Private.Checked ? "Y" : "N";
connection.connection1();
if (connection.con.State == ConnectionState.Closed)
connection.con.Open();
using (SqlCommand cmd = new SqlCommand("SaveImage", connection.con))
{
cmd.Parameters.Add("#privatecheck", SqlDbType.Char).Value = privateItem;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
connection.con.Close();
}
Basically I have a stored procedure in my database that will save my information.
Now what I was thinking to update one value is to basically do the same thing but it resulted in an error for me.
Any help on how to overwrite a previously saved checkbox value would be extremely helpful!
Thanks
I am not entirely clear on what you are asking for so my answer gives two possible solutions:
If you are looking to modify whether or not the control itself is checked or not checked here is a piece of sample code from MSDN:
private void AdjustMyCheckBoxProperties()
{
// Change the ThreeState and CheckAlign properties on every other click.
if (!checkBox1.ThreeState)
{
checkBox1.ThreeState = true;
checkBox1.CheckAlign = ContentAlignment.MiddleRight;
}
else
{
checkBox1.ThreeState = false;
checkBox1.CheckAlign = ContentAlignment.MiddleLeft;
}
// Concatenate the property values together on three lines.
label1.Text = "ThreeState: " + checkBox1.ThreeState.ToString() + "\n" +
"Checked: " + checkBox1.Checked.ToString() + "\n" +
"CheckState: " + checkBox1.CheckState.ToString();
}
If instead you are looking to modify a column in a table, an UPDATE SQL statement will do that for here, MSDN has a nice walkthrough on how to use LINQ and SQL to achieve this which I would recommend reading.
However I see you are using SqlCommand so here is the example code on how to perform an update command (again) from MSDN:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
All of the above pieces should help you generate a solution.
Hai all,
I want to get lookupedit display text when am giving correspond edit value.
example:
if am giving
LookupEdit1.Editvalue="3";
then it should show display text of Editvalue="3"
please help
//code
cmbChemical.Properties.DataSource = _lab.selectChemicals();
cmbChemical.Properties.DisplayMember = "labitem_Name";
cmbChemical.Properties.ValueMember = "labItem_ID";
cmbChemical.Properties.BestFitMode = BestFitMode.BestFit;
cmbChemical.Properties.SearchMode = SearchMode.AutoComplete;
cmbChemical.Properties.Columns.Add(new LookUpColumnInfo("labitem_Name", 100, "Chemicals"));
cmbChemical.Properties.AutoSearchColumnIndex = 1;
You can't, at least not in the way you're trying. The LookUpEdit, as the name implies, looks up its values in a DataSource, eg. a collection of objects. Therefore, to display the value 3 you need to have a list of objects that contains this value and set it as a DataSource for the control.
List<string> values = new List<string>();
values.Add("3");
lookUpEdit.Properties.DataSource = values;
lookUpEdit.EditValue = "3";
Maybe if you specify what are you trying to do, we can help you achieve that.
I think you don't have to specify display member or value member to get your needed behaviour. Following code give me a form with the lookupedit correctly showing "4", and i can choose other values from the list too.
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
public class Form1 : Form
{
public Form1()
{
var lookUpEdit1 = new LookUpEdit();
Controls.Add(lookUpEdit1);
var source = new List<string>();
for (var i = 0; i < 10;i++ )
source.Add(i.ToString());
lookUpEdit1.Properties.DataSource = source;
lookUpEdit1.EditValue = "4";
}
}
Maybe you get wrong results because you set display member and value member of the control.
This code worked for me.
private void lookUpEdit1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show((e.OriginalSource as SLTextBox).Text);
}
}