Sure you can, but the Validating even it self will do nothing. You have to put the code inside of it, ok ?
Mitja
Sure you can, but the Validating even it self will do nothing. You have to put the code inside of it, ok ?
Mitja
You can test is in this way:
put on the from:
- textBox
- button
- label
Now create a method for a button_Click event and put use this code on it:
private void button1_Click(object sender, EventArgs e)
{
string sValue = textBox1.Text;
int intValue = 0;
decimal decValue = 0M;
bool bValidating = int.TryParse(sValue, out intValue);
if (!bValidating)
{
bValidating = decimal.TryParse(sValue, out decValue);
if (!bValidating)
label1.Text = sValue + " is a string";
else
label1.Text = sValue + " is a decimal";
}
else
label1.Text = sValue + " is a integer";
}
Hope it helps,
Mitja
What do you want to validate? Stirng, int, double, bool?
Placing the files in the solution folder won't do anything, you have to
tell the solution to add new project/files. Chose File->Add Project-
>Existing Project and then browse to your individual project files (.csproj
files). You can also right click your solution name and Add->Existing
Items to add individual files in case you don't have a project.
I'm not quite sure what you are trying to do. You can put a whole bunch
projects in a single solution, but if you got more than one static void
Main() in the solution you won't be able to run it with F5/Ctrl-F5. You
can however compile a single project by right clicking the project name in
the solution explorer and choose Build.
If you have a bunch of files with static void Main() in several, comment
out the ones you don't want to run. F5/Ctrl-F5 will then work just fine
and will Compile, then run.
How you are going to open these 3 forms? Will you open 1 and then by clicking something on form1, this has to close and open form2, and so on?
1. You can simply use hide() method for the form you want NOT to show anymore (ps: but it has to be opened before).
2. You can open form2, and just after that you can call form1.Close() method.
I did some example code, how your control (in my example is this listView) moves togethe with the form.
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;
namespace Dec31ControlResize
{
public partial class Form1 : Form
{
int cWidth, cHeight;
int fWidth, fHeight;
public Form1()
{
InitializeComponent();
listView1.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
cWidth = listView1.Width;
cHeight = listView1.Height;
fWidth = this.Width;
fHeight = this.Height;
}
private void Form1_Resize(object sender, EventArgs e)
{
int diffWidth = this.Width - fWidth;
int diffHeight = this.Height-fHeight;
diffWidth = cWidth + diffWidth;
diffHeight = cHeight + diffHeight;
listView1.Size = new Size(diffWidth, diffHeight);
}
}
}
Hope it helps,
Mitja
Would you like that the control keeps the same ratio in any size of the form? So that the control shrinks and enlarges together with the form size?
Does your table get filled up?
If not, please try to change your query select string with this one:
string query = "SELECT Extrausage FROM perclientreport WHERE Bill > '" + 0 + "'";
and about updating:
double ext = Convert.ToDouble(dt.Rows[i]);
ext = (ext * 1024) / 100;
string str2 = "UPDATE perclientreport SET Bill = '" + ext + "'";
Hope it helps,
Mitja
Change this row to:
this.dgvSubContractor[3, row].Value.ToString() = c.CheckingValue(e.Value.ToString()).ToString();
and btw, this is not a good way to check for the number. What happenes in case if the string you check in the "CheckingValue" method is not a number? In your case nothing, only the form of tel. number will not the ok (maybe tel. number will include letters).
And your checking method here is completely wortheless - why? Because in any case you return string. Even ifs its not a number.
You have to set the method to bool modifier and return true or false. If true, set the string to a tel. number format, if not, warn the user he entered wrong string.
Something like:
private void PopulatingDGV()
{
//... code
if (e.ColumnIndex >= 0)
{
if (this.dgvSubContractor.Columns[e.ColumnIndex].Name == "TelNo")
{
if (e.Value != null)
{
string value = e.Value.ToString();
bool bChecking = c.CheckingValue(value);
if (bChecking)
this.dgvSubContractor[3, row].Value.ToString() = String.Format("{0:(###) ###-####}", value);
else
MessageBox.Show("Wrong tel. number format. Please repair it...");
}
}
return;
}
}
public static bool CheckingValue(string item)
{
long value = 0;
bool bChecking = long.TryParse(item, out value);
if (bChecking)
return true;
else
return false;
}
Hope this helps,
Mitja
If it was, please mark the thread as answered.
thx
Mitja
Whats this method: c.CheckingValue() ?
On form load call this method:
private void ResizingForm()
{
this.Width = 1024;
this.Height = 768;
}
If you still want to use Array list you can use the code bellow, but you need to seperate id ,and book name, (and id has to be converted to string):
ArrayList list = new ArrayList();
while (reader.Read())
{
int idBook = (int)reader[0];
string nameBook = (string)reader[1];
list.Add(idBook.ToString() + "-" + nameBook);
}
Because, you are retreiving onyl two different values from db, you can use Directory with key (id) and value (book name).
Dictionary<int, string> list = new Dictionary<int, string>();
while (reader.Read())
{
int idBook = (int)reader[0];
string nameBook = (string)reader[1];
list.Add(idBook, nameBook);
}
I am glad it gave you an idea. The example was meant that way, because you didnt even say what exactly do you want in your 1st post.
Le know know if its in any help, if not I`ll try to do better.
Mitja
Try this:
decimal moneyvalue = 1234567890.09m;
string html = String.Format("{0:C}", moneyvalue);
Sure, thats natural that you will not get any results if you stated to look for a user with all three fileds (in a where clause).
If you state "... WHERE name = @name AND last = @last AND social = @social"; the query will always look for results based on all three values - all three values have to be included in the result, if you want to get what you stated in the SELECT statement.
But there are some other ways to ran over it. Maybe you can seperate the query in some parts. The point is that the code 1st checkes (looks) for the data based on all three parameters (name, last and social), if there is none found the code will go through ones again, but with different query.
See the example:
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.SqlClient;
namespace Dec27Exercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<string> GetData(string name, string last, string social)
{
List<string> list = new List<string>();
using (SqlConnection sqlConn = new SqlConnection("YourConnString"))
{
using (SqlCommand cmd = new SqlCommand())
{
bool bContinue = true;
while (bContinue)
{
bool bReapeat = false;
string sqlQuery = null;
if (bReapeat)
{
sqlQuery = "SELECT UserName, LastName, Social FROM Users " +
"WHERE UserName = @name AND LastName = @last";
}
else
{
sqlQuery = "SELECT UserName, LastName, Social FROM Users " + …
Check this out.
This suits more to your example. I have did the code that you can use it directly, you only have to create methosd for inserting and retreiving data into/from dataBase.
This is the code now:
//form1:
public partial class Form1 : Form
{
delegate void DelegateDGV(DataTable table);
public Form1()
{
InitializeComponent();
CreatingDGV();
}
private void CreatingDGV()
{
dataGridView1.Columns.Add("column1", "first name");
dataGridView1.Columns.Add("column2", "last name");
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AllowUserToAddRows = false;
}
public void PopulatingDGV()
{
DataTable table = GetDataFromDB();
if (dataGridView1.InvokeRequired)
{
this.Invoke(new DelegateDGV(UpdatingDGV), new object[] { table });
}
}
private DataTable GetDataFromDB()
{
DataTable table = new DataTable();
//code for selecting data from db
return table;
}
private void UpdatingDGV(DataTable table)
{
dataGridView1.Rows.Clear();
foreach (DataRow dr in table.Rows)
{
//populate dgv from dr, like:
int rows = dataGridView1.Rows.Count;
rows++;
dataGridView1[0, rows].Value = dr[0].ToString();
dataGridView1[1, rows].Value = dr[1].ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show(this);
}
}
public class Users
{
public string firstName { get; set; }
public string lastName { get; set; }
}
}
//form2:
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 _form1)
{
InitializeComponent();
form1 = _form1;
}
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
string last = textBox1.Text;
// INSTEAD OF PASSING PARAMETER TO FORM1 (LIKE i DO HERE), YOU DO AN INSERT STATEMENT INTO DB.
//AFTER THAT CALL THE METHOD ON FORM1 (LIKE I DO: form1.PopulatingDGV(); - WITH NO …
Here is an example code I did for you:
//form1:
namespace Dec27Delegates
{
public partial class Form1 : Form
{
delegate void DelegateDGV(List<Users> list);
public Form1()
{
InitializeComponent();
CreatingDGV();
}
private void CreatingDGV()
{
dataGridView1.Columns.Add("column1", "first name");
dataGridView1.Columns.Add("column2", "last name");
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AllowUserToAddRows = false;
//adding a row just for info:
List<Users> list = new List<Users>();
Users user = new Users();
user.firstName = "Mitja";
user.lastName = "Bonca";
list.Add(user);
UpdatingDGV(list);
}
public void PopulatingDGV(List<Users> list)
{
if (dataGridView1.InvokeRequired)
this.Invoke(new DelegateDGV(UpdatingDGV), new object[] { list });
else
UpdatingDGV(list);
}
private void UpdatingDGV(List<Users> list)
{
foreach(Users user in list)
dataGridView1.Rows.Add(user.firstName, user.lastName);
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show(this);
}
}
public class Users
{
public string firstName { get; set; }
public string lastName { get; set; }
}
}
//form2:
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 _form1)
{
InitializeComponent();
form1 = _form1;
}
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
string last = textBox1.Text;
List<Users> list = new List<Users>();
Users user = new Users();
user.firstName = name;
user.lastName = last;
list.Add(user);
form1.PopulatingDGV(list);
}
}
As you can see I pass data directly from from2 to form1, where I show them in dgv.
What you have to do, is to save (do an insert statement) while on form2, and then you call the same method as mine on form1, which updates dgv. Only your method will get the data from dataBase, …
You will have to use delegates.
Hi, if you dont mind, you can send me whole project with the databse on my mail, I`ll take a look (I have an advantage, becuase I know your native language :) ).
mailto: <<Snipped>>
Mitja
I have repaired your code in the loop to:
case "Part time":
partTimeEmployees Employee = new partTimeEmployees (
fnameTextBox.Text,
LnameTextBox.Text,
//Convert.ToDecimal(fixedWeeklySalaryTextBox.Text),
Convert.ToDecimal(hourlyPayTextBox.Text),
Convert.ToDouble(totalHoursTextBox.Text),
Convert.ToDecimal(overTimePayTextBox.Text));
totalEarningLabel.Text = "" + Employee.ToString() + "\r\n\n Weekly Earning : "
+ Employee.Earnings().ToString("C") + "";
break;
..and now works, but Iam not sure if its correct. Now its on you to check it out.
PROBLEM WAS: you didnt pass the same npumber of arameters from button Click event to the constructor of the class "partTimeEmployees". And neither the value types werent the same (decimal, double).
Hope it helps,
Mitja
You know whats the problem with your code, you can pass to the constructor of the class (partTimeEmployees) only 3 parametes, but in your switch loop "partTime", you pass them 5. You have to change them to 3, or re-edit the constructor.
Mitja
... etc you go buy your self a book and do some basic study on it.
damn, what kind of answer is that? String, Int and Decimals?
hmmm.... etc?
Are you kididng me?
Better start with something else then programming, becuase with such an attitude, you will hardly find any help at all.
You are done with me....
bye
LOL - do you want us to help you?
If so, can you be a bit more precise?
Explain which values yu have in textBoxes, which one you want to pass to dgv, and least, which values you want to pass to database? And how is you database` table made of (what fields does it have)?
Why would you like to transfer data from textBoxes to DataGridView, and from there to db?
Or did you mean to dataTable, and from here to db?
string myEnum =MyEnum.A.Tostring();
You mean actaully printing with priner on the paper?
If so, best way would be to use reports (Crystal reports for example, which VS 2008 has). On the report you create your own parameters and pass values to these parameters.
Here is the code which shows you both:
(ps: button click even reverses the list, so you can see the difference in the code)
public Form1()
{
InitializeComponent();
string[] array = new string[] { "D", "C", "A", "E", "B" };
Array.Sort(array);
listBox1.Items.AddRange(array);
}
private void buttonInvert_Click(object sender, EventArgs e)
{
int rows = listBox1.Items.Count;
string[] array = new string[rows];
for(int i=0;i<listBox1.Items.Count;i++)
{
array[i] = listBox1.Items[i].ToString();
}
Array.Reverse(array);
listBox1.Items.Clear();
listBox1.Items.AddRange(array);
}
Ok, you are a bit unclear here with the issue you are facing.
Would you like to populate listBox with already sorted items, or would you like to sort items, which are already in the listBox?
Why you use index of the row of array (and the same index is then in the dgv)?
Why you simple dont use where clause to the ID?
For example:
your dgv`s row consists of: ID, name, ext (adivce: put id into 1st column)
So when you sort the columns (any of them), the row will still have the same data (id, name nad ext). So you only compare the name with the id.
What I am suggesting here it. that you get the new name, based on the row`s id, not on the row index of dgv.
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error message");
}
You`re welcome.
If there is anything you would like to know, just go ahead and ask.
And please, don`t forget to mark the thread as answered, if we`ve answered on your question. If there is another question in your mind, please start a new thread.
bye
Mitja
YOu names the class as "MAP" and the same name is the method in it.
The constructor can be the only method which can have the same name as the class.
Example:
class ExampleClass
{
public ExampleClass()
{
//constructor of class ExampleClass!
}
private void Method1()
{
//method in ExampleClass
}
private string Method2()
{
method in ExampeClass
string a = null;
//some code in here
return a;
}
}
remember... no method or even handler can have the same name as the class name (except the class`s constructor).
If you wanted to have some code in the constructor, you can not declare the return type.
You can see the example of constructor declarations here.
Hope this helps,
Mitja
If you dont use the sign "@" on the beginning of the path`s string, you have to write double back slashes for seperating folder. Example:
string path1 = @"C:\myFoler\myFile.txt";
string path2 = "C:\\myFolder\\myFile.txt";
I hope you see the difference between these two examples.
Mitja
If you got the answer on your question, can you please mark the thread as answered please?
thx
Mitja
as Momerath said:
ThisList.Clear();
if you want to read the file from the debuf folder in your current project you simply bind the text file, like:
string startupPath2 = Application.StartupPath + @"\something.txt"; //or maybe without backslash! try it(I am doing this code by my heart).
string startupPath1 = System.IO.Directory.GetCurrentDirectory();
//or:
string startupPath2 = Application.StartupPath;
This will return the path of the debug diredctory in the current project.
If you want to check if something has happened with the code correctly or not, you better use boolean values. This is a simpe example:
private void GoingIntoMAP()
{
string path = @"C:\1\myFile.txt";
bool bSuccess = MAP(path);
if (bSuccess)
MessageBox.Show("An error has occured while reading file: " + path);
else
MessageBox.Show("File has beed read successfully."); //but this is not necessary to show, only errors or warnings!
}
public bool MAP(string FilePath)
{
using (FileStream fs = new FileStream(FilePath, FileMode.Open))
{
try
{
//read the file and stuff you want to do!
//on the end:
return true;
}
catch
{
return false;
}
}
}
I hope this explains the concept of catching error.
Do some examples and you will see this is the best way.
Mitja
My question: do you want to have numbers seperated with a whitespace, or together?
Your question: Depends how do you want to.
If you know what the 3 is on 2nd place from the right, you can access to it like:
string str1 = "1357";
string str2 = "1 3 5 7";
string a1 = str1.Substring(1,1);
string a2 = str2.Substring(2, 1);
I have already showed how to do this:
//use the full upper code:
if (line.Contains(','))
{
line = line.Replace(",", "");
Numbers.Add(line);
}
In the 1st part? What is that suppose to mean?
Did you mean in the same row?
SORRY, but PLEASE.... START ANOTHER THREAD!
You question has been answered plenty of times. Even from my side.
Hope you understand the issue.
Mitja
This should do it:
But I am not sure what do you want exactly. Or do you want to put every single number from the file into its own row in the List (like: 1,3,7,9 add evey number to the list seperately), or you want to "join" number from one row (like : 1,3,7,9 join into 1379 and add this number to the list)?
This is the code:
FileStream aFile = new FileStream("SomeData.txt", FileMode.Open);
List<NewList> Numbers = new List<NewList>();
using (StreamReader sr = new StreamReader(aFile))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
//1.Putting every number into its own row in the list<T>:
string[] array = line.Split(',');
for (int i = 0; i < array.Length; i++)
Numbers.Add(array[i].ToString()); //you can remove ToString() method if not needed
//2.Putting all number into one row (removing commas from original):
if (line.Contains(','))
{
line = line.Replace(",", "");
Numbers.Add(line);
}
}
}
If this is not it, please exaplin a bit better what exactly would you like to do with the numbers, ok?
Mitja
you could mark this thread as solved using the mark as solved link above the quick reply box. That way I actually get credit for helping you.
Its about time :)
Yes, and?
Please tell us whats the matter? Is it working or not?
Otherwise I did some minor changes in your code, please let me know if its working (if not, please check the connection string).
private static string _connectionString = @"Data Source=TROJANX;Initial Catalog=ENTERPRISE4;Integrated Security=True;Pooling=False";
private void a()
{
using (SqlConnection sqlConn = new SqlConnection(_connectionString))
{
using (SqlCommand sc = new SqlCommand())
{
sc.CommandType = CommandType.Text;
sc.CommandText = "select * from laitem";
sc.Connection = sqlConn;
sqlConn.Open();
using (SqlDataReader sr = sc.ExecuteReader())
{
while (sr.Read())
{
Console.WriteLine(sr["itemid"].ToString() + " Item: " + sr["itemname"].ToString());
Console.ReadLine();
}
}
sqlConn.Close();
}
}
}
You can create a new connection from Server Explorer and copy connection strings from properties in your project. Following link contains steps to create connection from Server Explorer
http://msdn.microsoft.com/en-us/library/s4yys16a(v=VS.90).aspx
You can try following Connectionstring
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
You can also get list of connection string from http://connectionstrings.com/sql-server-2008
Hope it helps,
Mitja
I would better suggest you to start with using text files, its way simplier and as efficient as xml (if not even more in your case, becuase you dont have millions of data).
You can use streamWriter to write into txt filen and streamReader to read out of it.
// *** Read from file ***
--------------------------
// Specify file, instructions, and privelegdes
file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);
// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);
// Read contents of file into a string
string s = sr.ReadToEnd();
// Close StreamReader
sr.Close();
// Close file
file.Close();
// *** Write to file ***
--------------------------
// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw = new StreamWriter(file);
// Write a string to the file
sw.Write("Hello file system world!");
// Close StreamWriter
sw.Close();
// Close file
file.Close();
Do you mean to close the project (completey)? If so, you have to save the data from listView somewhere, or into some file (xml, text), or into database. Otherwise, how will you retrive the data? When program is closed, all data gets lost. So the only way to retreive them back is to get them from somewhere were they were saved before - you get the point now?