I'm trying to make a search bar that searches in the Access database table with multiple criteria.
When I type in the search bar a number it will do the search just fine, but when I delete what's in the search bar it shows me this error:
System.Data.SyntaxErrorException:
'Syntax error: Missing operand after '=' operator.'
And when I type a character it shows me this error:
'System.Data.EvaluateException: 'Cannot find column [a].'
Note:
the Chamber field is type number, long integer.
Here is the code:
private void ResSearchtextBox_TextChanged(object sender, Eventers e)
{
Data View dv = dt.DefaultView;
dv.RowFilter = "(Name LIKE'%" + ResSearch_textBox.Text + "%') OR (Surname LIKE'%" + ResSearch_textBox.Text + "%') OR (Chamber =" + ResSearch_textBox.Text + ")";
ResDGV.DataSource = dv;
}
What I've tried:
private void ResSearchtextBox_TextChanged(object sender, EventArgs e)
{
DataView dv = dt.DefaultView;
dv.RowFilter = "(Name LIKE'%" + ResSearch_textBox.Text + "%') OR (Surname LIKE'%" + ResSearch_textBox.Text + "%') OR (Chamber ='" + ResSearch_textBox.Text + "')";
ResDGV.DataSource = dv;
}
The issue you're seeing is because the RowFilter property expects a string in the format of an SQL WHERE clause, and you are trying to use it to filter based on the value in the ResSearch_textBox control. When the text box is empty, the RowFilter property is being set to "(Name LIKE'%%') OR (Surname LIKE'%%') OR (Chamber =)", which is causing the error you mentioned. When you type a character in the text box, the RowFilter property is being set to "(Name LIKE'%a%') OR (Surname LIKE'%a%') OR (Chamber ='a')", which is causing the second error you mentioned.
To fix these issues, you can add some logic to your code to handle the case where the text box is empty. One way to do this is to check the length of the text in the text box, and only apply the filter if the length is greater than 0. You can also use the TryParse method to try converting the text in the text box to a number, and only apply the Chamber = filter if the conversion is successful.
If there is no value in ResSearch_textBox, the formatted row filter will be, in part, ...OR (Chamber =) in the first case,and ...OR (Chamber = ''), in the second. The first is invalid SQL, as the error indicates. The second might be a database error, because if the Chamber field is expected to be a number, ’’ can’t be converted to one. The solution depends on what you want to happen if there is no chamber filter. If you don’t want to do the query at all, you could add code to the handler to skip the query if there’s no value. You could also substitute a default value — 0, maybe? — instead of a blank.
The error is pretty clear, then the value of the textbox is empty in that case it becomes something like (Name LIKE'%%') OR (Surname LIKE'%%') OR (Chamber =) and hence there is no value after = that is why you are seeing the Syntax error: Missing operand after '=' operator.' error.
your second error looks related to the datatype.
when you have only an a character in that case RowFilter is trying to compare with the string value but the Chamber datatype is different.
so you should add a check like before this code if (searchText == "" || add other checks here) { return; }
Related
I am writing Insurance Managment System as project at University.
This is my MySQL commadn:
string lifeQuery = "insert into lifeinsurance values( null, '" + surname.Text + "." + pesel.Text + "', " + double.Parse(lifeInsSumTB.Text) + ", '" + double.Parse(lifeInsPriceTB.Text)
+ ");";
But te problem is that in UWP double is with ',' and to MySQL i need to have it with '.'.
When I try to do this like this: '25,453' it says data truncated. Without ' ', like this 25,453 it says that column count doesn't match value count at row 1, because it interets it as two different values 25 and 453.
So my question is:
How do I insert this double value to my table?
This problem is caused by the implicit conversion to a string when you call double.Parse and then concatenate the result back into the sql text. This requires the compiler to represent the double value as a string and it will use the current culture to do the conversion. Of course the result is not what MySql expect to be a double value.
Moreover using string concatenation to build sql commands leads to Sql Injection hacks. A very nasty problem that you should avoid. Always.
So let's try to add some code to resolve these problems
// A parameterized string without any concatenation from user input
string lifeQuery = #"insert into lifeinsurance
values( null, #surname, #sum, #price)";
MySqlCommand cmd = new MySqlCommand(lifeQuery, connection);
// Add the parameters with value for each placeholder in string
cmd.Parameters.AddWithValue("#surname", surname.Text + "." + pesel.Text);
// Parse the user input as a double using the current culture to correctly
// interpret the comma as decimal separator.
// Note that here I have no check on the correctness of the input. If your
// user cannot be trusted to type a valid double number then you should use
// the double.TryParse approach separating these lines from the actual check
cmd.Parameters.AddWithValue("#sum", double.Parse(lifeInsSumTB.Text, CultureInfo.CurrentCulture));
cmd.Parameters.AddWithValue("#price", double.Parse(lifeInsPriceTB.Text, CultureInfo.CurrentCulture));
cmd.ExecuteNonQuery();
Like other said - there are better ways to send over data with Sql. That being said this answer focuses on addressing your specific problem.
I think your problem may be your language/culture settings.
Try this:
Console.WriteLine(double.Parse("19.2323244").ToString("G", CultureInfo.InvariantCulture));
Output:
19.2323244
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netcore-3.1#Invariant
I have an SQL query and it has comma value. When I adding it to DataGridView I want to this format (#, ##). I tried Math.Round() function but it doesn't work.
Below is the query I have tried:
(CONVERT(DECIMAL(18, 2), column3)*100) as normalize
It's my C# code for adding;
dgv.Rows.Add(rows["column1"].ToString() + " " + rows["column2"].ToString(), rows["column3"], "%" + "" + Math.Round(Convert.ToSingle(rows["normalize"].ToString())), 2);
It runs without comma with this code. Normally, If I don't use Math.Round it works like this format (#, ####).
And I tried this one also;
dgv.Columns[2].DefaultCellStyle.Format = "N2";
How should I fix it?
Try this, add the value type property, it works on my case.
dgv.Columns[2].DefaultCellStyle.Format = "N2";
dgv.Columns[2].ValueType = typeof(Double);
Full code sample
object[] row = new object[] { 6.54553 };
dataGridView1.Rows.Add(row);
dataGridView1.Columns[0].DefaultCellStyle.Format = "n2";
dataGridView1.Columns[0].ValueType = typeof(double);
i would like to filter a datatable by a column which contains number data, i'm trying the following:
string selected = colSelect.GetItemText(colSelect.SelectedItem);
if (filterText.Text.Length == 0)
{
data_table.DefaultView.RowFilter = string.Empty;
}
else
{
data_table.DefaultView.RowFilter = string.Format("Price Like '%{0}%'", filterText.Text);
I've tried casting the second value to a string but no luck, i get the error:
Cannot perform 'Like' operation on System.Decimal and System.String
The data entered would be any number or text, but based on the data only relevant number values would show with the filter.
Looks like Price column is decimal typed but you supplied a string which is filterText.Text to filter it.
One solution might be using CONVERT which is explained in DataColumn.Expression documentation like;
data_table.DefaultView.RowFilter = "CONVERT(Price, 'System.String') like '%" + filterText.Text + "%'";
I didn't tried this one but you can parse your filterText.Text to decimal (if it is valid one) and use it like;
data_table.DefaultView.RowFilter = "Price Like '%" + decimal.Parse(filterText.Text) + "%'";
But as I said, I an not %100 sure for the second one.
I have this Oracle 11g table
CREATE TABLE "DBNAME"."CANDIDATES"
(
"ID" NUMBER(24,0),
"USRINS" VARCHAR2(30 CHAR),
"DATINS" DATE,
"USRUPD" VARCHAR2(30 CHAR),
"DATUPD" DATE,
"EXM_ID" NUMBER(24,0),
"TYPE" NUMBER(3,0),
"PSN_ID" NUMBER(24,0),
"KOD" NUMBER(20,0),
"STATUS" NUMBER(20,0),
"PRICINA" VARCHAR2(200 CHAR)
)
Now i have this command in C#
string insertIntoCandidates = "INSERT INTO CANDIDATES " &
"(USRINS, DATINS, PSN_ID, KOD, STATUS, PRICINA) " &
values ("
+ ":usrins, "
+ ":datins, "
+ ":psn_id, "
+ ":kod, "
+ ":status, "
+ ":pricina"
+ ") ";
command.Parameters.Add(":usrins", null);
command.Parameters.Add(":datins", DateTime.Now);
command.Parameters.Add(":psn_id", getPsnIDByEMBG(result.embg));
command.Parameters.Add(":kod", result.kod_kandidat);
if (result.status)
{
command.Parameters.Add(":status", 1);
}
else
{
command.Parameters.Add(":status", 0);
}
command.Parameters.Add(":pricina", result.pricina);
int res = command.ExecuteNonQuery();
The columns for which I don't insert a value, can get null values.
After executing the last line, I get am exception ORA-01722: invalid number. I tried looking for an answer, but without any luck. Could you help me out? Thanks
add
command.BindByName=true;
apparently Oracle defaults to positional binding instead of name binding.
An ORA-01722 ("invalid number") error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a valid number. So, check the parameters for correct data types.
And also see:
C# parameterized queries for Oracle - serious & dangerous bug!
and
Why am I getting an ORA-01722 (invalid number)?
Further to michaos's answer, also note that it doesn't matter what you name your parameters, they have to be added in the order in which they appear in the query. If not, then you can get misleading ORA-01722 (and other) errors. Yes this is a horrible bug!
Instead of null you have to use DBNull.Value
private void btnKaydet_Click(object sender, EventArgs e)
{
MessageBox.Show(" Sayin " + txtAdi.Text + txtSoyadi.Text
+ " " + "Kredi Miktari=" + txtMiktar.Text.ToString() + "TL"
+ Environment.NewLine + "Aylik Odeme=" + nmrVade.Value + "TL",
MessageBoxButtons.YesNo
);
}
How can I solve this 2 errors ?
Error 2 Argument 2: cannot convert from 'System.Windows.Forms.MessageBoxButtons' to 'string' C:\Users\LEVENT\Desktop\bilge adam\week1_day3\WinBatanBank\WinBatanBank\Form1.cs 23 189 WinBatanBank
Error 1 The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string, string)' has some invalid arguments C:\Users\LEVENT\Desktop\bilge adam\week1_day3\WinBatanBank\WinBatanBank\Form1.cs 23 13 WinBatanBank
1 and 2) MessageBox doesn't have an overload for (string, MessageBoxButtons). You'll need to use the overload for (string Text, string Title, MessageBoxButtons Buttons)
MessageBox.Show("Display Text Here", "Box Title Here", MessageBoxButtons.YesNo);
Let's go over the errors and see what they mean.
Error 2 Argument 2: cannot convert from 'System.Windows.Forms.MessageBoxButtons' to 'string'
This means the function is expecting a parameter of type string, but you supplied a parameter of type System.Windows.Forms.MessageBoxButtons. If it was possible to convert your parameter to a string, you wouldn't get this error. So this can be fixed by supplying a string.
Error 1 The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string, string)' has some invalid arguments
This means that your call to the function is incorrect. You could have multiple errors like the first one (where multiple parameters are incorrect), and you'd also get one error like this one. It means that the compiler thinks you want to supply two string parameters, but it appears you haven't done so.
In Visual Studio, when you are typing code, you often get a little box with suggestions. This is the IntelliSense feature. If you carefully read the box, you'll see what you need to supply as the next parameter.
Another option is to look at the official documentation. If you search for msdn messagebox.show with your favourite search engine, you'll quickly find a link to http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.show.aspx
It has a list of overloads, that's basically a list of all possible parameter combinations. Look at the name or the description to find the one you want to use, or to find the most similar one to what you're currently trying to do.
MessageBox.Show has a relatively large number of overloads but none that take only a string and MessageBoxButtons as parameters. You can try to use this overload which takes 2 strings, text and caption, followed by MessageBoxButtons:
private void btnKaydet_Click(object sender, EventArgs e)
{
MessageBox.Show(
" Sayin " +txtAdi.Text + txtSoyadi.Text + " "+ "Kredi Miktari=" + txtMiktar.Text.ToString()+"TL" + Environment.NewLine + "Aylik Odeme=" + nmrVade.Value+"TL",
"Some Caption",
MessageBoxButtons.YesNo);
}
You've used the wrong amount/combination of arguments.
Try to add a messagebox title:
MessageBox.Show( " Sayin " +txtAdi.Text + txtSoyadi.Text + " "+ "Kredi Miktari=" + txtMiktar.Text.ToString()+"TL" + Environment.NewLine + "Aylik Odeme=" + nmrVade.Value+"TL",
"messageBoxTitle",
MessageBoxButtons.YesNo);