How to get the integer value in TextBox? - c#-4.0

I have one Text Box in windows application. This Text Box only allowed the integer value not string. Can anybody have solution ?

Convert it.
public int GetIntValue(TextBox tb)
{
try
{
return Convert.toInt32(tb.Text);
}
catch (Exception ex)
{
//This is called if the converting failed for some reason
}
return 0; //This should only return 0 if the textbox does not contain a valid integer value
}
Use it like this:
int number = GetIntValue(textBox1);
Hope this helps!

Use this.
int value = Convert.ToInt32(textBox1.Text);
You use this code and get your integer value.Thanks

I found a solution from C# How do I make a textbox that only accepts numbers
Hope it will help you.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}

Related

lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem

I try to put a file into a richtext but it crashes !
In my first code, I try to use directly "getFirstItem", in first time it was ok but now i try to use it again and it crashed.
In second time i pass with an object and it find my obj doesn't an richtextItem (instanceof) ???
I don't understand.
I have the message : "lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem" ?
Could you help me ?
public void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) throws NotesException {
lotus.domino.Session session = Utils.getSession();
lotus.domino.Database db = session.getCurrentDatabase();
lotus.domino.Document monDoc = db.getDocumentByUNID(idDocument);
lotus.domino.RichTextItem rtiNew = null;
try {
try {
if (monDoc != null) {
// if (monDoc.getFirstItem(nomRti) != null) {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.getFirstItem(nomRti);
// } else {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.createRichTextItem(nomRti);
// }
Object obj = null;
if (monDoc.getFirstItem(nomRti) != null) {
obj = monDoc.getFirstItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
} else {
obj = monDoc.createRichTextItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
}
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
}
} finally {
rtiNew.recycle();
monDoc.recycle();
db.recycle();
session.recycle();
}
} catch (Exception e) {
e.printStackTrace();
}
}
EDIT : I try to modify my code with yours advices but the items never considerate as richtextitem. It is my problem. I don't understand why, because in my field it is a richtext ! For it, the item can't do :
rtiNew = (lotus.domino.RichTextItem) item1;
because item1 not be a richtext !!!
I was trying to take all the fields and pass in the item one by one, and it never go to the obj instance of lotus.domini.RichTextItem....
Vector items = doc.getItems();
for (int i=0; i<items.size(); i++) {
// get next element from the Vector (returns java.lang.Object)
Object obj = items.elementAt(i);
// is the item a RichTextItem?
if (obj instanceof RichTextItem) {
// yes it is - cast it as such // it never go here !!
rt = (RichTextItem)obj;
} else {
// nope - cast it as an Item
item = (Item)obj;
}
}
A couple of things. First of all I would set up a util class method to handle the object recycling in a neater way:
public enum DominoUtil {
;
public static void recycle(Base... bases) {
for (Base base : bases) {
if (base != null) {
try {
base.recycle();
} catch (Exception e) {
// Do nothing
}
}
}
}
}
Secondly I would remove the reduntants try/catch blocks and simplify it like this:
private void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) {
Session session = DominoUtils.getCurrentSession();
Database db = session.getCurrentDatabase();
Document monDoc = null;
try {
monDoc = db.getDocumentByUNID(idDocument);
Item item = monDoc.getFirstItem(nomRti);
if (item == null) {
item = monDoc.createRichTextItem(nomRti);
} else if (item.getType() != Item.RICHTEXT) {
// The item is not a rich text item
// What are you going to do now?
}
RichTextItem rtItem = (RichTextItem) item;
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtItem.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
} catch (NotesException e) {
throw new FacesException(e);
} finally {
DominoUtil.recycle(monDoc);
}
}
Finally, apart from the monDoc, you need not recycle anything else. Actually Session would be automatically recycled and anything beneath with it (so no need to recycle db, let alone the session!, good rule is don't recycle what you didn't instantiate), but it's not bad to keep the habit of keeping an eye on what you instantiate. If it were a loop with many documents you definitively want to do that. If you also worked with many items you would want to recycle them as early as possible. Anyway, considered the scope of the code it's sufficient like this. Obviously you would call DominoUtil.recycle directly from the try block. If you have multiple objects you can recycle them at once possibly by listing them in the reverse order you set them (eg. DominoUtil.recycle(item, doc, view)).
Also, what I think you miss is the check on the item in case it's not a RichTextItem - and therefore can't be cast. I put a comment where I think you should decide what to do before proceeding. If you let it like that and let the code proceed you will have the code throw an error. Always better to catch the lower level exception and re-throw a higher one (you don't want the end user to know more than it is necessary to know). In this case I went for the simplest thing: wrapped NotesException in a FacesException.

what's different between StrCmpW and wcscmp?

Actually i changed code to next.
struct myclass {
bool operator() (std::wstring p1, std::wstring p2) {
int result = 0;
//// If character is alphabet, sorting need converse.
wint_t a1 = p1.at(0);
wint_t b2 = p2.at(0);
int r1 = iswalpha(a1);
int r2 = iswalpha(b2);
**// return code of iswalpha.
// 257 is Upper Alphabet,
// 258 is Lower Alphabet**
if ((r1 == 257 && r1 == 258) ||
(r2 == 258 && r2 == 257)) {
result = p2.compare(p1);
}
else {
result = p1.compare(p2);
}
if (result != 0) {
if (result == -1) {
return true;
}
else {
return false;
}
}
return false;
}
} wStrCompare;
void main() {
std::vector<std::wstring> wlist;
wlist.emplace_back(L"가나");
wlist.emplace_back(L"123");
wlist.emplace_back(L"abc");
wlist.emplace_back(L"타파");
wlist.emplace_back(L"하하");
wlist.emplace_back(L"!##$");
wlist.emplace_back(L"一二三");
wlist.emplace_back(L"好好");
wlist.emplace_back(L"QWERID");
wlist.emplace_back(L"ⓐⓑ");
wlist.emplace_back(L"☆★");
wlist.emplace_back(L"とばす");
std::sort(wlist.begin(), wlist.end(), wStrCompare);
}
Test Result
L"!##$"
L"123"
L"abc"
L"QWERID"
L"ⓐⓑ"
L"☆★"
L"とばす"
L"一二三"
L"好好"
L"가나"
L"타파"
L"하하"
is this good?
Please give me a some opinion.
Thanks!!
I change my code, but i still want to know "is there difference between StrCmpW and wcscmp" Please talk to me. thanks!
Old question
I use qsort with std::wstring(for unicode string), and use StrCmpW.
Previously, I used StrCmpLogicalW() with CString, CStringArray.
(These are depend on windows)
But my code run in linux too, not only in windows.
(CString is ATL(afx), StrCmpLogicalW() is in Shlwapi.h)
So I use std::wstring and wcscmp, but result is different.
Is there a difference between StrCmpW() and wcscmp()?
The Following is my code.(exactly not mine lol)
int wCmpName(const void* p1, const void *p2)
{
std::wstring* wszName1 = ((std::wstring *)(p1));
std::wstring* wszName2 = ((std::wstring *)(p2));
int wret = StrCmpW(wszName1->c_str(), wszName2->c_str());
// int wret = wcscmp(wszName1->c_str(), wszName2->c_str());
// When i use wcscmp, different result comes out.
return wret;
}
void wSort(std::vector<std::wstring> &arr)
{
qsort(arr.data(), arr.size(), sizeof(std::wstring), wCmpName);
}
Thanks!
Test Code
void main() {
std::vector<std::wstring> wlist;
wlist.emplace_back(L"가나");
wlist.emplace_back(L"123");
wlist.emplace_back(L"abc");
wlist.emplace_back(L"타파");
wlist.emplace_back(L"하하");
wlist.emplace_back(L"!##$");
wlist.emplace_back(L"一二三");
wlist.emplace_back(L"好好");
wlist.emplace_back(L"QWERID");
wlist.emplace_back(L"ⓐⓑ");
wlist.emplace_back(L"☆★");
wlist.emplace_back(L"とばす");
wSort(wlist);
}
Test Result
wcscmp
L"!##$"
L"123"
L"QWERID"
L"abc"
L"ⓐⓑ"
L"☆★"
L"とばす"
L"一二三"
L"好好"
L"가나"
L"타파"
L"하하"
StrCmpW
L"!##$"
L"☆★"
L"123"
L"ⓐⓑ"
L"abc"
L"QWERID"
L"とばす"
L"가나"
L"一二三"
L"타파"
L"하하"
L"好好"
p.s : WHY limit reputation?! limited Images, limited URLs.
Only text takes so long time.

Trying to get a valid integer from keyboard input

I am trying to get a valid integer from the user input, the function I wrote must display an error message for these inputs..
1) 0 or a negative number
2) a string
It works for strings but not for 0 or negative numbers
I am unable to find my mistakes.. :-(
public int getValidNumber()
{
int temp_int;
while ((!int.TryParse(Console.ReadLine(), out temp_int)) && (temp_int > 0))
{
Console.WriteLine("Not a valid number....try again");
}
return temp_int;
}
Is it the correct way to use temp_int variable immediately....?
The most obvious mistake is that your while runs if the int is greater than 0, which you don't want:
//Assign to temp_int first:
int.TryParse(Console.ReadLine(), out temp_int);
while (temp_int < 1)
{
Console.WriteLine("Not a valid number....try again");
int.TryParse(Console.ReadLine(), out temp_int);
}
getValidNumber(Console.ReadLine());
...
public int getValidNumber(string input)
{
int temp_int = int.TryParse(input, out temp_int);
if (temp_int =< 0)
{
Console.WriteLine("Not a valid number....try again");
}
return temp_int;
}

using like operator in if operator in C#

I have a textbox for search (that is, textBox1)
A user, for example, enters "aba" in textBox1.
"abandon" puts in datagridiew1.
The user clicks on datagriview1:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
richTextBox_MWE.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
if ("richTextBox_MWE.Text like '%" + textBox1.Text + "%'")
{
label5.BackColor = Color.Green;
}
}
I want if "abandon" is such as "aba" in textBox1, label5.BackColor becomes Green.
Simple way is use the textBox1(where actually filter content going to change) change event
if(!String.IsNullOrEmpty(richTextBox_MWE.Text) && richTextBox_MWE.Text.Trim().Contains(textBox1.Text.Trim()))
{
label5.BackColor = Color.Green;
}
You want to use some kind of mix of C# and sql :) You can use the String.Contains method to achieve what you want.
if(richTextBox_MWE.Text != null
&& richTextBox_MWE.Text.Contains(textBox1.Text.Trim())
{
...
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
richTextBox_MWE.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
if (!String.IsNullOrEmpty(richTextBox_MWE.Text) && !String.IsNullOrEmpty(textBox1.Text) && richTextBox_MWE.Text.Contains(textBox1.Text.Trim()))
{
label5.BackColor = Color.Green;
}
}
Here the contains will accept the value to be searched.
See snippet from my code. The txtProductCode is a text box that user is filling the product_code for searching in the list view.
string tmpProductCode = txtProductCode.Text.Trim();
string tmpProductCodePattern = "^" + Regex.Escape(tmpProductCode).Replace("%", ".*") + "$";
In my loop of product_code(s) the prodCode will contain the product_code value for each loop.
productCodeClause = false;
if (tmpProductCode.Equals(""))
{
productCodeClause = true;
}
else
{
if (Regex.IsMatch(prodCode, tmpProductCodePattern))
{
productCodeClause = true;
}
}
I hope this will be helpful.

searching in List<>

i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
try
{
//decimal find = decimal.Parse(txtnapsaserach.Text);
if (decimal.Parse(txtnapsaserach.Text) > 0)
{
List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();
}
}
catch (Exception Ex)
{
}
}
any solution for me . Because this works for me when i try to find string value.
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
float value;
if (!float.TryParse(txtnapsaserach.Text, out value))
return; // return if text cannot be parsed as float number
if (value > 0)
{
var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
napsaTableBindingSource.DataSource =
napsatabs.Where(p =>p.NapsaRate == value).ToList();
}
}
try this
i want to find value in List<> but i am not getting the integer value.
Your p.NapsaRate is either integer type or floating point number, (probably decimal) Convert your txtnapsaserach.Text to decimal value and then compare it in where clause.
decimal rate = 0;
if(!decimal.TryParse(txtnapsaserach.Text), out rate)
{
//Invalid number in textbox
}
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate == rate)).ToList();
if p.NapsaRate is of type double or float you can parse them accordingly using Double.TryParse or Double.Parse etc
The reason you are not getting any error is that you are using object.Equals method for comparing decimal value with string. You should always use == for equality comparison of value types.

Resources