C# Split() in ListBox - c#

listBox2 contents:
0:FirstProduct
1:ProductAgain
2:AnotherProduct
3:OkFinalProduct
What I'm trying to do, when the selected index has changed on listBox2, is to have it make my int "DBID" the value of the number before the ":".
Here's my attempt:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex == -1)
{
return;
}
int DBID;
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
ShowProduct(DBID);
}
ANY help with this is greatly appreciated :)
Thanks guys
EDIT -
Sorry, yes I actually tried:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
but im getting the following errors:
The best overloaded method match for string.Split(params char[])' has some invalid arguments
Argument1: cannot convert from 'string' to 'char[]
EDIT #2 -
When using:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
After running the application and clicking on a different listbox item, I'm encountering this exception:
NullReferenceException was unhandled. Object reference not set to an instance of an object.
I appreciate all the help so far guys!

Try changing:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
To:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
Update
Try this instead. It explicitly adds a new char:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(new char[] { ':' })[0]);

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);

A safer way will be to replace the single statement with the following code,
if (listBox3.SelectedValue != null)
{
string selectedValue = listBox3.SelectedValue.ToString();
if (!string.IsNullOrEmpty(selectedValue))
{
if (Int32.TryParse(selectedValue.Split(':')[0], NumberStyles.Integer, CultureInfo.CurrentCulture, out DBID))
{
// Process DBID
}
else
{
// Cannot convert to Int32
}
}
}
Then use breakpoints in the code, to find where the NullReferenceException is occurring.
Note that this example assumes that you are using System.Windows.Controls.ListBox or System.Windows.Forms.ListBox, and not System.Web.UI.WebControls.ListBox. In the later case, the SelectedValue is a string and not an object (as pointed out by #Srinivas Reddy Thatiparthy in another answer's comment)

Related

Displaying a character count while the user is typing?

I'm trying to build a program with that displays the number of characters and words while a user is typing into the text box. I thought I knew what I was doing but ran into this error:
'Cannot implicitly convert type 'string' to
'Systems.Windows.Forms.Label'
This is what I have so far. The last line of code contains the error:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
string userInput = userTextBox.Text;
char charCount;
charCount = userInput[0];
charCountOutput = charCount.ToString();
}
1) You need to set the property on the Label to set the text
charCountOutput.Text = ...
2) The length of a string can be accessed through the Length property
charCountOutput.Text = userInput.Length.ToString();
charCountOutput.Text = charCount.ToString();
Assuming charCountOutput is the label
Your code is trying to assign the Label object the value of a string, which is a type mismatch (obviously).
You're assigning to a textfield, changing the text of the field.
charCountOutput.Text = charCount.ToString();
int countChar = userTextBox.Text.ToString().Length;
Here's a late addition - you probably already have seen this, but here's a really fast approach. Assumes charCountOutput is label on your form:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
var userInput = userTextBox.Text;
charCountOutput.Text = userInput.Length.ToString();
}

Input string was not in correct format any tips?

On the previous page i have
protected void SqlCheckout_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
string CustID;
if (e.Exception == null)
{
CustID = e.Command.Parameters["#CustomerID"].Value.ToString();
Response.Redirect("Payment.aspx?id=" + CustID);
}
}
Then on my payment page
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
int intCustID;
int intOrderID;
intCustID = int.Parse(Request.QueryString["CustomerID"]);
//save shopping cart
ShoppingCart objCart;
//retreive shoppping cart from session
objCart = (ShoppingCart)Session["shoppingCart"];
//the shopping cart cannot be empty
if (objCart != null)
{
//save Cart
intOrderID = objCart.SaveCart(intCustID);
e.Values["OrderID"] = intOrderID;
Session["OrderID"] = intOrderID;
}
else
{
e.Cancel = true;
}
}
Im following a tutorial EDIT: That allows me to insert data into a database, and for some reason at this line of code Im getting an error saying Input string was not in correct format EDIT: and The ' value cannot be null' ... any tips?
The querystring parameter id is not an integer.
If you're unsure of the validity of a parameter, use TryParse instead.
int intCustId;
if(int.TryParse(Request.QueryString["id"], out intCustId)
{
// Do stuff
}
else
{
// Handle error
}
First, make sure Request.QueryString["id"] is not null or empty.
int intCustID = string.IsNullOrEmpty(Request.QueryString["id"]) ? 0 : int.Parse(Request.QueryString["id"]);
This will:
Check if your Request.QueryString["id"] is null or empty.
if yes, it will return zero otherwise, it will parse the string to int
Assign parsed int value to intCustID
You can also use :
int intCustID = Convert.ToInt32(Request.QueryString["id"]);
Based on your comment:
Im getting an error saying Input string was not in correct format
EDIT: and The ' value cannot be null' ... any tips?
It sounds like when you arrive on this page you do not have id in the query string. So most likely your url looks like this:
http://mysite.com/mypage.aspx
and it needs to look like this:
http://mysite.com/mypage.aspx?id=1234
In order to fix this you will most likely need to go to the previous page (the page that you navigate TO the page with the error FROM) and figure out why id isn't getting passed in the query string.
UPDATE
Your original code suggested you were trying to pull:
Request.QueryString["id"]
While your update suggests:
Request.QueryString["CustomerID"]
Based on your comment below neither of these are correct. You need to match the query string exactly (including case). Try the code below:
Request.QueryString["ID"]
As other's have mentioned you should probably be using TryParse also.
This means that the the string that Request.QueryString["id"] returns is not an integer.
What you get is probably either
empty, so that you are trying to convert an empty string
a non-numeric string, which obviously cannot be converted to an integer
a decimal format number, like "5.0", instead of "5", which also would give this exception. In that case you can use double.Parse instead, and convert to int afterwards.

Simple "realtime" search using listview and streamreader

I'm attempting to make a simple realtime search using a streamreader to read from a txt file and search and display the results in a listview, problem is I can only search for 1 letter, so searching for "1" will show me results for everything starting with 1, example search 1 results in "123", but searching for "12" or "123" wont show the same result. Easier explained with this code I've tried.
Edit, text-file I'm reading from has this structure:
123;asd;asd;asd;asd;asd;asd <- example of a row
public static string[] testtt(string sökord)
{
StreamReader asd = new StreamReader("film.txt");
string temp;
string[] xd;
while (asd.Peek() >= 0) // if I can read another row (I.E next row isnt empty)
{
temp = asd.ReadLine();
xd = temp.Split(';');
for (int i = 0; i < xd.Length; i++)
{
// this should check if my searchword is equal to any member of "xd"
// but this is where the problem occurs when the input is more than 1
// character, will post error message from debugger below this code.
if (xd[i].Substring(0, sökord.Length).ToLower() == sökord.ToLower())
return xd;
}
}
return null;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
listView1.Items.Clear();
ListViewItem item = new ListViewItem(testtt(textBox1.Text)[0]);
item.SubItems.Add(testtt(textBox1.Text)[1]);
item.SubItems.Add(testtt(textBox1.Text)[2]);
item.SubItems.Add(testtt(textBox1.Text)[3]);
item.SubItems.Add(testtt(textBox1.Text)[4]);
item.SubItems.Add(testtt(textBox1.Text)[5]);
item.SubItems.Add(testtt(textBox1.Text)[6]);
listView1.Items.Add(item);
if (textBox1.Text == "")
listView1.Items.Clear();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
ex
{"Index and length must refer to a location within the string.\r\nParameter name: length"} System.Exception {System.ArgumentOutOfRangeException}
This is fairly simple. This error will always appear when the line you have read form the stream reader, and you split and store the value in xd. Say the length of xd is n. And the sokord string you entered has say m length. Now when you write:
(xd[i].Substring(0, sökord.Length)
whenever the length of xd that is n is less than m, the Substring function would be trying to make a substring of m letters from only n letters. And hence it gives the error you mentioned.
In any case just a simple check should do ok:
String sString = null;
if(xd[i].length>=sokord.length){
sString = xd[i].SubString(0,sokord.length).toLower();
if(sString.equals(sokord.toLower()))
return xd;
}
Digvijay
PS: To be honest I have written the answer from what best I could understand of what is trying to be done, so the code might be a little offtrack in one scenario. But in any case the error i have described above is 100% correct. So it would be best if you just look into that and follow the track. =)
Still dont know if I understood the question correctly, but wouldnt this be much easier to read and understand?
private String[] FindSome(String searchword)
{
foreach (String s in System.IO.File.ReadLines("myfile.txt"))
{
String[] tmp = s.Split('c');
foreach (String t in tmp)
{
if (t.StartsWith(searchword,StringComparison.CurrentCultureIgnoreCase)) return tmp;
}
}
return null;
}

Unable to cast Combobox.SelectedValue

My code goes like this for simple practise problem which i am trying to build. I come across
Invalid Cast Exception. Specified Cast is not valid.
public Form1()
{
Combobox1.Datasource = foo.bar.dataset.tables[0];
Combobox1.DisplayMember = "Name";
Combobox1.ValueMember = "ID";
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
NewClass P2 = new NewClass;
P2.Filter.Id = (long)Combobox1.SelectedValue;
}
Can anyone tell me why is this happening and how to go about solving it even though I have typecasted Combobox1.SelectedValue object?
Maybe this will help:
P2.Filter.Id = Convert.ToInt64(Combobox1.SelectedValue);
According to your comment this might help:
P2.Filter.Id = Convert.ToInt64((Combobox1.SelectedValue as DataRowView).Item[0]);
I'm not sure why this happens, maybe someone can help me on that but I would prefer going.
P2.Filter.Id = Convert.ToInt64(Combobox1.SelectedValue);
That always works for me when I have this issue.
ComboBox.SelectedValue is obviously not a long. You should do whatever is required to change its type; most probably this would be
P2.Filter.Id = Convert.ToInt64(ComboBox1.SelectedValue);
Check the object reference before you cast SelectedValue.
long value=0l;
if (comboBox1.SelectedValue != null)
{
value=long.Parse(comboBox1.SelectedValue.ToString());
}
You can use SelectedItem property which will returns the reference of DataRowView (row).
DataRowView row = comboBox1.SelectedItem as DataRowView ;
if (row != null){
MessageBox.Show("value " + row[0] + " " + row[1]);
}
Casting a string to long is mal-casting. SelectedValue is supposed to return a string that needs Convert.ToLong to operate on
Convert.ToInt64(Combobox1.SelectedValue)
Rather try something like
Convert.ToInt64
Converts a specified value to a 64-bit signed integer.
At some later stage you might also want to take a look at using
Int64.TryParse Method
Converts the string representation of a number to its 64-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded or failed.
or Int64.Parse Method
Converts the string representation of a number to its 64-bit signed
integer equivalent.
Thickness t = new Thickness(0);
if (value != null)
{
t= new Thickness(System.Convert.ToInt64(((System.Windows.Controls.ComboBoxItem)value).GetValue(System.Windows.Controls.ComboBoxItem.ContentProperty)));
}
return t;

Checking value from Combobox(string) without ToString C#

I'm doing a project where "ToString" is being used as a method.
private void button1_Click(object sender, EventArgs e)
{
if(cboPlaneType.SelectedItem = "Generic")
{
}
else if (cboPlaneType.SelectedIndex = "Passenger")
{
}
else if (cboPlaneType.SelectedIndex = "Fighter Jet")
{
}
}
And in this case i'm not sure what to do. As you can see I've tried a few different option but with no avail. I've also tried
if((string)cboPlaneType.SelectedItem = "Generic")
And that didn't work.
**Edit
Just to point out, SelectedValue wasn't the correct answer.
ended up being "if((string)combobox.SelectedItem == "Generic")
The equality operator in c# is ==; = is an assignment operator.
SelectedIndex will return an int representing the zero-based position of the item that is selected. (I'm guessing it returns -1 when no item is selected.)
SelectedItem can be an object of any type; if it is not a string then you can't match it by comparing with a string.
Are you saying that the objects with which the ComboBox is populated override ToString()? You should still be able to use the result of that method for comparison, because it can only return a string. Otherwise, you might be able to use SelectedValue, but this depends on what kind of ComboBox you are using and how you have set it up.
SelectedIndex is an property of type Int32.
Maybe you want to use SelectedValue instead ?

Categories

Resources