Weird issue in c# related to DataSet - c#

I'm currently working on a program that converts japanese characters to english characters and the other way around.
It's not working much though, For the last few days I've been trying everything to try and get it to work, it's probably some small dumb problem but I just can't find it. I'm pretty new to all this so any help is appreciated.
Now the problem is that it only wants to convert Romaji characters, however if change some code, more specifically if I change the following from "if" to else if, then it converts hiragana and katakana but NOT romaji..
string fromtype = "";
// Determines what type the character is currently
// && fromtype == "" added to avoid weird unexplainable errors...
if (CharacterTable.Select("Romaji = '" + character + "'") != null && fromtype == "")
{
fromtype = "Romaji";
}
else if (CharacterTable.Select("Hiragana = '" + character + "'") != null && fromtype == "")
{
fromtype = "Hiragana";
}
else if (CharacterTable.Select("Katakana = '" + character + "'") != null && fromtype == "")
{
fromtype = "Katakana";
}
I've even tried removing this function that tries to automatically find what type the character is and do it with radiobuttons so that the user has to select it, but somehow it seems to do pretty much the same thing... So I'm totally confused at this point, any help is very much welcome.
Here is the full code:
public string CheckCharacter(string character, int RequestedCharType)
{
// RequestedCharType
// 1 = Romaji
// 2 = Hiragana
// 3 = Katakana
//-- Instantiate the data set and table
DataSet CharacterDatabase = new DataSet();
DataTable CharacterTable = CharacterDatabase.Tables.Add();
//-- Add columns to the data table
CharacterTable.Columns.Add("Romaji", typeof(string));
CharacterTable.Columns.Add("Hiragana", typeof(string));
CharacterTable.Columns.Add("Katakana", typeof(string));
//-- Add rows to the data table
CharacterTable.Rows.Add("a", "あ", "ア");
CharacterTable.Rows.Add("i", "い", "イ");
// Sets fromtype to the type the character(s) currently is/are
string fromtype = "";
// Determines what type the character is currently
// && fromtype == "" added to avoid weird unexplainable errors...
if (CharacterTable.Select("Romaji = '" + character + "'") != null && fromtype == "")
{
fromtype = "Romaji";
}
else if (CharacterTable.Select("Hiragana = '" + character + "'") != null && fromtype == "")
{
fromtype = "Hiragana";
}
else if (CharacterTable.Select("Katakana = '" + character + "'") != null && fromtype == "")
{
fromtype = "Katakana";
}
// generates a new variable to store the return in
DataRow[] filteredRows = CharacterTable.Select(fromtype + " = '" + character + "'");
// Return the converted character in the requested type
foreach (DataRow row in filteredRows)
{
if (RequestedCharType == 1)
{
return row["Romaji"].ToString();
}
if (RequestedCharType == 2)
{
return row["Hiragana"].ToString();
}
if (RequestedCharType == 3)
{
return row["Katakana"].ToString();
}
}
// if it couldn't find the character, return the original character
return character;
}

Your problem is in your misunderstanding of how Select works. Select does not return null when there are no matches so your first if is always true. Instead you need to check whether there were any results which you can do with Enumerable.Any() (add using System.Linq):
if (CharacterTable.Select("Romaji = '" + character + "'").Any())
{
fromtype = "Romaji";
}
else ...
Alternatively you can check the array length:
if (CharacterTable.Select("Romaji = '" + character + "'").Length > 0)
{
fromtype = "Romaji";
}
else ...
I'm not sure what the fromType == "" bit is all about this is surely not needed.
Considering creating an enum type for your char types.
This method can be made static.
Consider using a switch statement instead of if (RequestedCharType == 1)
&c.

Related

System.Data.EvaluateException HResult=0x80131920 Message=Cannot perform '=' operation on System.Int32 and System.String

public void MatchedDocumentsInFileCabinet(string MainFolder, string SubFolder, string FileName, string FilePath)
{
// Checking Main Folder is present in FileCabinet, if present retrieving MainFolderID if not Inserting MainFolderName
if (SelectedFileCabinetID == "")
{
SelectedFileCabinetID = "1";
}
int Mainfoldercount = 0;
DocSortResult getfolderdetails = objFolderManager.GetFolderDetails();
DataTable getFolderNames = new DataTable();
if (getfolderdetails.resultDS != null && getfolderdetails.resultDS.Tables[0].Rows.Count > 0)
{
// Following line is showing error
DataRow[] drResult = getfolderdetails.resultDS.Tables[0].Select("FileCabinet_ID = '" + SelectedFileCabinetID + "'" + "and" + " ParentFolderID = '" + "0" + "'" + "and" + " IsDelete = '" + "True" + "'");
if (drResult.Count() != 0)
{
getFolderNames = drResult.CopyToDataTable();
}
}
}
Without knowing getfolderdetails.resultDS.Tables[0] structure is hard to know which column is, but one of those columns is integer and your Select(filter) is telling that all the fields are string.
An example of your code debugging would show .Select("FileCabinet_ID = '4' and ParentFolderID = '0' and IsDelete = 'True' "). And the error message says one of them is not a string.
I would bet that IsDelete = 'True' probably will be boolean (bit column in SQL Server) and FileCabinet_ID or ParentFolderID or both of them are integer (and this is causing the error).
Set a breakpoint and check the datatypes of the datacolumns you are trying to filter.

Search data gridview using textbox and checkboxlist asp.net c#

I want to use textbox and checkboxlist to search data in gridview using asp.net c#. Using textbox can search the data. But for checkboxlist only can search the data when check only one checkbox. If check more than one checkbox, can't search the data. thanks a lot for helping.
the code:
c# code
protected void btnSearch_Click(object sender, EventArgs e)
{
if (cblDay.SelectedIndex != -1)
{
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
RptRateData.Day += val.Value + "";
}
}
}
RptRateData.RateAmount = txtRate.Text.Trim();
BindGrid();
}
code for class:
public string RateAmount { get; set; }
public string Day { get; set; }
internal DataSet GetRptRateSet()
{
DataSet tmpDS = new DataSet();
try
{
string strSQL = #"SELECT ComplexRateInfo.ComplexRateId,
ComplexRateDetailInfo.Day,
ComplexRateInfo.RateAmount
FROM ComplexRateInfo
LEFT JOIN ComplexRateDetailInfo ON ComplexRateInfo.ComplexRateId = ComplexRateDetailInfo.ComplexRateId ";
string whereSQL = " WHERE";
string orderBySQL = " order by Day ;";
int filterCount = 0; //to keep track of needed filter that are going to be used by the sql string
string[] sIndex = new string[2]; //to keep track of scalar variable needed by the sql, four string of sIndex because maximum filter available is 4
int indexCount = 0; //count to access sIndex members
//filter with or without day
if (_ds.Day != null && _ds.Day != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.Day;
indexCount++;
}
//filter with or without rate amount
if (_ds.RateAmount != null && _ds.RateAmount != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.RateAmount;
indexCount++;
}
//build complete query with no filter at all
if (filterCount == 0)
{
strSQL = strSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL));
}
//build complete query with 1 or more filter
else
{
strSQL = strSQL + whereSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL, sIndex));
}
}
catch (Exception ex)
{
throw ex;
}
return tmpDS;
}
There are two mistakes in your code.
Assigning values to RptRateData.Day from CheckBoxList.
Description: You assign selected values to object without using any separator. So For example if you have selected 1, 2, 4 days then as per your code, value of RptRateData.Day will be 124. Instead of that, it should be separated with comma as shown below:
var selectedDays = string.Empty;
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
selectedDays += "'" + val.Value + "',";
}
}
RptRateData.Day = selectedDays.TrimEnd(new char[] { ',' });
Now come to the second point which is in your SQL query which you make dynamically.
Description: In this query in WHERE clause you use Like operator for ComplexRateDetailInfo.Day. This will not work anymore. Instead of that you should use IN operator.
Note: Are you sure that your Like operator is working with curly braces ('{' and '}') and without '%' symbol ?

Postback not working on mouse click in Safari

So I have a dropdown context box, which I use to select which item I am going to be working with.
Now everything seems to be working on all browsers except Safari. I have a type function that works fine in safari if you focus on the box and type the name in and hit enter. However my issue is with the mouse click. If I select an item from the dropdown and click it, the postback doesn't work until I hit enter on the keyboard.
Here is my .ascx.cs file
...
if (cboContext.Visible)
{
string postBackFunction = "function contextPostback() {\n"
+ "var newValue = document.getElementById(\"" + cboContext.ClientID + "\").value;\n"
+ "if (newValue != " + cboContext.SelectedValue + ") " + Page.ClientScript.GetPostBackEventReference(cboContext, "") + ";\n}";
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "contextPostback", postBackFunction, true);
if (Request.UserAgent.ToLower().IndexOf("chrome") > -1)
{
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
else if (Request.UserAgent.ToLower().IndexOf("safari") > -1)
{
cboContext.Attributes.Add("onclick", "contextPostback();");
cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onkeyup", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
}
else
{
cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
cboContext.Attributes.Add("onclick", "contextPostback();");
}
}
Here is the typeAhead() function
function typeAhead(e, nextFocus) {
//don't trap Ctrl+keys
if ((window.event && !window.event.ctrlKey) || (e && !e.ctrlKey)) {
// timer for current event
var now = new Date();
....
if (inputBuffer.accumString == "" || now - inputBuffer.last < inputBuffer.delay) {
//check for browsers
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
// make shortcut event object reference
var evt = e || window.event;
// get reference to the select element
var selectElem = evt.target || evt.srcElement;
// get typed character ASCII value
var charCode = evt.keyCode || evt.which;
// get the actual character, converted to uppercase
var newChar = "";
// get reference to the actual form selection list
// added cross browser fix to enable the context switcher to work properly
if (is_chrome) {
var selection = document.getElementById("ctl00_ContextSwitch1_cboContext").selectedIndex;
}
else {
var selection = document.getElementById(nextFocus);
}
....
Now I have a section in the typeAhead for the chrome browser, but everything I try for safari doesn't seem to allow me to use the mouse click to select an item.
Any help would be appreciated.
simple fix. safari recognizes onchange so once I added that, it worked fine.

Problems with if and else if, c#

I'm trying to make a program that converts japanese characters into english characters but I have a weird problem and I cant figure out what how to solve it, I did find out what caused it though.
I'm using a dataset and I'm using this code to convert the characters
My problem is that it doesn't want to convert certain characters, and the characters it doesn't want to convert are based on what I set here:
// Sets fromtype to the type the character(s) currently is/are
string fromtype = "";
if (CharacterTable.Select("Romaji like '%" + character + "%'") != null)
{
fromtype = "Romaji";
}
else if (CharacterTable.Select("Hiragana like '%" + character + "%'") != null)
{
fromtype = "Hiragana";
}
else if (CharacterTable.Select("Katakana like '%" + character + "%'") != null)
{
fromtype = "Katakana";
}
If I change every individual line to "if", then it doesn't want to recognise romaji characters, if i set it to "else if" like right now, it sees.
Here is the full code:
DataSet CharacterDatabase = new DataSet();
DataTable CharacterTable = CharacterDatabase.Tables.Add();
//-- Add columns to the data table
CharacterTable.Columns.Add("Romaji", typeof(string));
CharacterTable.Columns.Add("Hiragana", typeof(string));
CharacterTable.Columns.Add("Katakana", typeof(string));
//-- Add rows to the data table
CharacterTable.Rows.Add("a", "?", "?");
// Sets fromtype to the type the character(s) currently is/are
string fromtype = "";
if (CharacterTable.Select("Romaji like '%" + character + "%'") != null)
{
fromtype = "Romaji";
}
else if (CharacterTable.Select("Hiragana like '%" + character + "%'") != null)
{
fromtype = "Hiragana";
}
else if (CharacterTable.Select("Katakana like '%" + character + "%'") != null)
{
fromtype = "Katakana";
}
// generates a new variable to store the return in
DataRow[] filteredRows = CharacterTable.Select(fromtype + " like '%" + character + "%'");
// Return the converted character in the requested type
foreach (DataRow row in filteredRows)
{
if (RequestedCharType == 1)
{
return row["Romaji"].ToString();
}
if (RequestedCharType == 2)
{
return row["Hiragana"].ToString();
}
if (RequestedCharType == 3)
{
return row["Katakana"].ToString();
}
}
// if it couldn't find the character, return the original character
return character;
You need to consider what happens if a character matches multiple types. It is possible that regardless of the if or if else, you choose a fromtype that doesn't have a matching result in the database.
You could consider some sort of scoring mechanism, where you query each type, and if the character matches multiple types, you take into consideration which types have replacements available.
You assume that DataTable.Select() returns a null when there is no match. It doesn't, it returns an empty array. Your test should look like this:
if (CharacterTable.Select("blabla").Length > 0) { // etc.. }

Dynamically setting LINQ datasource results in Operator '==' incompatible with operand types 'String' and 'Int32'

I'm trying to dynamically set my where statements for a linq datasource, and it was working fine until I try to add another constraint.
This code works here:
private void SetDataSourceWhereStatement()
{
HttpCookie cookie = Request.Cookies[ "CustomerID" ];
if ( cookie == null ) //set data source where statement to default
ldsCustomerLinks.Where = "CustomerID == -1";
else ldsCustomerLinks.Where = "CustomerID == " + cookie.Value; //set data source where statement
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID;
ldsCustomerLinks.DataBind();
}
However, when I also try and add a customer number, I get the error. This is the code I'm attempting to use:
private void SetDataSourceWhereStatement()
{
HttpCookie cookie = Request.Cookies[ "CustomerID" ];
HttpCookie cookie2 = Request.Cookies[ "CustomerNumber" ];
if ( cookie == null ) //set data source where statement to default
ldsCustomerLinks.Where = "CustomerID == -1";
else ldsCustomerLinks.Where = "CustomerID == " + cookie.Value; //set data source where statement
if ( cookie2 != null )
ldsCustomerLinks.Where += " && CustomerNumber == " + cookie2.Value;
// else ldsCustomerLinks.Where += " && CustomerNumber >= 0";
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID;
ldsCustomerLinks.DataBind();
}
Both cookie and cookie2 values are strings. I've tried converting it using int.parse, int32.parse, using the value's .toString() methods and trying everything all over. I don't understand what's wrong.
EDIT::
So I got my answer, from one of the below posts, but I do not understand, could someone please explain why my original code did not work but the revised does?
Old code:
if ( cookie2 != null )
ldsCustomerLinks.Where += " && CustomerNumber == " + cookie2.Value;
New code:
if ( cookie2 != null )
ldsCustomerLinks.Where += #" && CustomerNumber == (""" + cookie2.Value + #""") ";
Forgive me, without much knowledge about this LINQ usage my answer might be totally off.
This question seems to be related though and suggests that you parse/convert the (quoted in that case!) value.
You say cookie and cookie2 are strings... what about m_CategoryID?
have you tried
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID.ToString();
OK - I was suspicious of the lack of quotes for CustomerNumber in the 'Where' string, but not confident enough to post it as a suggestion (having a bad SO day!)
So to answer the second question:
the type mismatch comes within the database, where CustomerNumber (I am inferring) is a string, but you are building a query with a number, like
CustomerID == 312 && CustomerNumber == 45654789 && CategoryID == 3
where you should be saying
CustomerID == 312 && CustomerNumber == "45654789" && CategoryID == 3
and to get the quotes within a string (which is enclosed by quotes) you need to use the """ syntax.

Categories

Resources