What happens? Nothing. It will not set it! Thats why its better to avoid such coding (as I explained up there). Its better to use code, and let user know that the (in your example) id is not long enough.
Im glad I can help,
bye
Mitja
What happens? Nothing. It will not set it! Thats why its better to avoid such coding (as I explained up there). Its better to use code, and let user know that the (in your example) id is not long enough.
Im glad I can help,
bye
Mitja
samsylvestertty:
So, for every new session (new game) started, I need a new port, am I right?
And, is DB really necessary? I think it would go without it.
Were you using tscListener and tcpClient for this kind of game?
Try to change the AND operators with OR:
If (textBox1.Text.Length < 5 || textBox2.Text.Length < 5 || textBox3.Text.Length < 5)
return false;
else
return true;
It should work now.
An example in console application how to join data tables:
One question: Do you have in both tables the same number of Ids?
If now, this code can give you an error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Okt17JoinTables
{
class Program
{
static void Main(string[] args)
{
DataTable tableBooks = new DataTable("books");
DataTable tableAuthors = new DataTable("authors");
DataTable tableJoin = new DataTable("books&authors");
DataColumn column;
DataRow row;
tableBooks.Columns.Add(new DataColumn("BookID", typeof(int)));
tableAuthors.Columns.Add(new DataColumn("AuthorID", typeof(int)));
//POPULATING TABLES WITH SOME VALUES:
int[] booksID = new int[] { 5, 4, 6, 2, 9 };
int[] authorsID = new int[] { 23, 12, 13, 24, 16 };
for (int i = 0; i < 5; i++)
{
row = tableBooks.NewRow();
row["BookID"] = booksID[i];
tableBooks.Rows.Add(row);
row = tableAuthors.NewRow();
row["AuthorID"] = authorsID[i];
tableAuthors.Rows.Add(row);
}
tableJoin.Columns.Add(new DataColumn("BookID", typeof(int)));
tableJoin.Columns.Add(new DataColumn("AuthorID", typeof(int)));
foreach (DataRow dr in tableBooks.Rows)
{
row = tableJoin.NewRow();
row["BookID"] = dr[0];
tableJoin.Rows.Add(row);
}
int counter = 0;
foreach (DataRow dr in tableAuthors.Rows)
{
row = tableJoin.Rows[counter];
row["AuthorID"] = dr[0];
counter++;
}
}
}
}
Maybe my understanding of creating such a game is wrong. There always HAS to be only one server, so only TcpListener. Thats becuase I have only one IP, on which clients can connect.
But how to create New games - what are New games? They cannot be Servers and can either cannot be Clients (clients only connect to the created game). This is something I cannot figure out.
Or the same example is MSN. MSN is one Server. So what are chat-rooms? I can talk with plenty users at the same time. How to define these created chat-rooms?
This was not a question, I know how to do a set method that can do a comparation, but in my opinion its better to use methods for these kind of actions.
What you need is a seperate method (maybe even in a new class) for checking the user name and password.
btw, where do you store usernames and their passwords? Do you use a database, or a file on hdd?
In any case, you need a new boolean method where you compare the inserted username with password. Return true or fase. If the username belongs to the password, return true, if not, return false. So if on form1 comes true, form is shown, if its false, you show an exception with messageBox ("username and password are wrong").
And this method you use every single time when you need a login.
Do you understand me?
An example code:
public class Login
{
public static bool LoginCheck(string name, string password)
{
bool bChecking;
//if you use database you do the ckecing:
//using sqlConnection...
string str = @"SELECT password FROM Users WHERE UserName = @userName";
//using sqlCommand....
cmd.Parameters.Add("@userName", SqlDBType.VarChar, 50).Value = name;
//...
//then you compare the password from query and the password inserted
//return true if passwords are equal:
bChecking = true;
//return false if they are different:
bChecking = false;
return bChecking;
}
}
}
if not, please feel free to ask for some additional info...
Mitja
if (textbox1.Text == 6) // this is to check if the string input is equal to 6 chars.
{
your code here
}
else
{
MessageBox.Show("The data you input is not valid or less than expected)
}if you want to set only 6 digits
then..private void studentID;
public int StudentID
{
get { return detailsID; }
set
{
if (studentID == 6)
{
studentID = value;
}
}this will definetely help you!
this will defenately NOT help you!
What you have stated is completely wrong! Please do not reply with such answers.
1. If you want to check the lenght of the string, so how many characters string has you have to do with string.Lengt property, and not with equalizing to the number, like you did (string == 6) - COMPLETELY WRONG; What you did its only comparing if the string has number 6, nothing else.
2.Your set method is again completely wrong. How the hack do you compare if the sting has 6 characters?
btw, do you know what it means 6 characters? This is not a string "6", but its a string that consists 6 different letters, number or signs (12ab,.) - that means 6 characters long.
Anyway, as I said, Get,Set method is not meant to do any checking (even if its possible to do it), but it`s meaning shows it`s …
This is an example where is shown everything you need. I did it only for you:
... I hope you like it, note: do a copy/paste to CONSOLE application, and try to run it!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Okt17GetSet
{
class Program
{
List<StudentInfo> studentList = new List<StudentInfo>();
static void Main(string[] args)
{
bool bChecking = false;
Program pro = new Program();
Console.WriteLine("Hi there,");
while (!bChecking)
{
Console.WriteLine("Do you want to ADD new or SEARCH for the student?");
Console.WriteLine("(1 - add, 2 - search, 3 - exit program)");
string strQuestion = Console.ReadLine();
if (strQuestion != null)
{
if (strQuestion == "1")
pro.AddingStudent();
else if (strQuestion == "2")
pro.GettingStudent();
else if (strQuestion == "3")
bChecking = true;
else
{
Console.WriteLine("Wrong answer, please do it again...");
continue;
}
}
}
Console.WriteLine("bye, bye...");
System.Threading.Thread.Sleep(1000);
Environment.Exit(0);
}
private void AddingStudent()
{
bool bChecking = false;
string strID = null;
string strName = null;
while (!bChecking)
{
Console.WriteLine("Please, insert students ID:");
strID = Console.ReadLine();
if (strID.Length >= 6)
{
while (!bChecking)
{
Console.WriteLine("Please insert student`s name:");
strName = Console.ReadLine();
if (strName.Contains(" "))
bChecking = true;
else
Console.WriteLine("Student needs to have name and last name...");
}
}
else
{
Console.WriteLine("Student`s ID is not long enough, it must be at least 6 characters...");
}
}
//when all ok, do an insertion into list of students:
//1. ADDING NEW STUDENT:
StudentInfo info = new StudentInfo();
info.StudentID = strID;
info.Name = strName;
studentList.Add(info);
Console.WriteLine("New student data saved into list!");
Console.WriteLine("ID: {0}, NAME: …
Check this out, and let me know if its helps:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Okt17GetSet
{
class Program
{
List<StudentInfo> studentList = new List<StudentInfo>();
static void Main(string[] args)
{
Program pro = new Program();
pro.GettingStudents();
}
private void GettingStudents()
{
bool bChecking = false;
string strID = null;
string strName = null;
while (!bChecking)
{
Console.WriteLine("Please, insert students ID:");
strID = Console.ReadLine();
if (strID.Length >= 6)
{
while (!bChecking)
{
Console.WriteLine("Please insert student`s name:");
strName = Console.ReadLine();
if (strName.Contains(" "))
bChecking = true;
else
Console.WriteLine("Student needs to have name and last name...");
}
}
else
{
Console.WriteLine("Student`s ID is not long enough, it must be at least 6 characters...");
}
}
//when all ok, do an insertion into list of students:
StudentInfo info = new StudentInfo();
info.StudentID = strID;
info.Name = strName;
studentList.Add(info);
Console.WriteLine("New student data saved into list!");
Console.WriteLine("ID: {0}, NAME: {1}", strID, strName);
Console.ReadLine();
}
}
public class StudentInfo
{
private string studentID;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string StudentID
{
get { return studentID; }
set { studentID = value; }
}
}
}
I would like to do the simple card game which can many people play at the same time, but not only one game, there can ne n games running.
Recently I was learning how to do server-client coding, using TcpListener and TcpClient network services. But the main difference between the past project and the project which I would like to do it, that the past one had ONLY ONE server. In the next one there will be more then just one server to make it work.
So when someone would like to start a new game, the new server thread has to create (and as many new client thread as many people will join to this server). But I am not sure how to explain this well, all I want is how users can start their own "new servers thread". And there servers threads have to come out of one code.
Simple example is a party poker game.
Can anyone point me to the right direction how and where to start, if it s a good idea of using tcpListener, and tcpClient network services, OR there is something else better for such project?
I would really appreaciate it for a fair and decent answer.
Mitja
ReplyQuote
Why would you need a database at all for only chat application? As somekind of a log?
Instead of that, you can simply use file (write to file).
Anyway, if you have decided to use db, it can only be on server side. But I am not really sure why you need db at all? If you explain why you need it, I can give you further information.
btw, what method have you taken for server-client?
Iam doing almost the same application, andI choose TpcListener and TcpClient (using ip). And I have problems. I am just wondering what type of connection have you taken!?
Just take it easy, get some book that you will get the basic knowledge. Even the internet has a lot of example code, but start with simple things, and do not let your self to get invalved into some serious and demanding project - at least not in the beginning (this usually takes from 1 -2 years).
The repaired code: (and I added the round function, to 2 decimal places):
class Program
{
static void Main(string[] args)
{
const int SQ_FT_PER_SQ_YARD = 9;
const int INCHES_PER_FOOT = 12;
const string BEST_CARPET = "Berber";
const string ECONOMY_CARPET = "Pile";
int roomLengthFeet = 12,
roomLengthInches = 2,
roomWidthFeet = 14,
roomWidthInches = 7;
double roomLength,
roomWidth,
carpetPrice,
numOfSquareFeet,
numOfSquareYards,
totalCost;
roomLength = roomLengthFeet +
roomLengthInches / INCHES_PER_FOOT;
roomWidth = roomWidthFeet +
roomWidthInches / INCHES_PER_FOOT;
numOfSquareFeet = roomLength * roomWidth;
numOfSquareYards = numOfSquareFeet /
SQ_FT_PER_SQ_YARD;
//1.
carpetPrice = 27.95;
totalCost = numOfSquareYards * carpetPrice;
totalCost = Math.Round(totalCost, 2);
string strTotal = String.Format("{0:C}", totalCost);
Console.WriteLine("The Cost of {0} is {1}", BEST_CARPET, strTotal);
Console.WriteLine();
//2.
carpetPrice = 15.95;
totalCost = numOfSquareYards * carpetPrice;
totalCost = Math.Round(totalCost, 2);
strTotal = String.Format("{0:C}", totalCost);
Console.WriteLine("The cost of {0} is {1}", ECONOMY_CARPET, strTotal);
Console.Read();
}
}
Hi, and welcome to programming...
If you are creating WinForms App or some other, 1st you create GUI, then you start creating the code, using the Controls (and their methods) putted onto the GUI.
This is for the beginnng.
When you will become a bit more advanced, you can create Controls and their methods by the code (You do not need to put them on the form - becuase when you manually put some control, lets say a TextBox on the form, C# automatically creates the code for it. Take a look into YourForm.Designer.cs file for the code).
Manual creation of the control and it`s method:
//CALL THIS METHOD IN FORM LOAD (OR SOMEWHERE BEFORE YOU INTEND TO USE THE TEXTBOX):
private void CreatingNewTextBox()
{
TextBox textBox1 = new TextBox();
textBox1.Name = "textBox1";
textBox1.Size = new Size(100, 20);
textBox1.Location = new Point(20, 20);
this.Controls.Add(textBox1);
textBox1.TextChanged += new EventHandler(textBox1_Click);
}
//CREATE NEW METOHD FOR TEXTBOX (THIS IS AN EXAMPLE, THERE IS PLENTY OF METHODS AVAILABLE):
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
I have created new new paper size in the windows (Print Server Properties > Create new form), with name: POPPaperSize (76mm x 150mm) - this has all know dimensions (width and height).
Then I did this code:
string printerName = GetPrinterName();
if (printerName != null)
{
System.Drawing.Printing.PrintDocument doctoprint = new System.Drawing.Printing.PrintDocument();
doctoprint.PrinterSettings.PrinterName = printerName;
int rawKind = 0;
for (int i = 0; i <= doctoprint.PrinterSettings.PaperSizes.Count - 1; i++)
{
if (doctoprint.PrinterSettings.PaperSizes[i].PaperName == "POSPaperSize")
{
rawKind = Convert.ToInt32(doctoprint.PrinterSettings.PaperSizes[i].GetType().GetField("kind",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes[i]));
break; // TODO: might not be correct. Was : Exit For
}
}
cr.PrintOptions.PaperSize = (CrystalDecisions.Shared.PaperSize)rawKind;
CrystalDecisions.Shared.PageMargins pMargin = new CrystalDecisions.Shared.PageMargins(0, 0, 0, 0);
cr.PrintOptions.ApplyPageMargins(pMargin);
crystalReportViewer1.ReportSource = cr;
cr.PrintToPrinter(1, false, 0, 0);
}
What I would like to know is how to change the code in case if I do not know the height of the paper. There is difference in the height if put 1 or 100 items on the paper (like the bill in the store).
I heard that I have to use Graphics objects, but I have no clue how... so please if someone can help me out. I would really appreciate it.
Mitja
Now I know the width of the paper. It`s 76mm (or 3 inches). But I DO NOT know the lenght. So how can I create a new custom paper if I dont know the lenght? As far as I know, the custom paper size consists of width and lenght, but there is one of them missing it is impossible to create it... or am I wrong?
If you can find one of the enumerated paper sizes that is the right width and length, I'd use that.
The width is not a problem, but the lenght, as I said it varies. Depends how much items its on it. So in this case it hard (or almost impossible) to use enumerated paper size.
But lets say if I do use one, how would I do it?
Hello, I am doing a C# win. application, and using crystal report for printing bills on a custom paper size The width of the paper is unknown (the program has to get the paper size - if this is possible), the lenth of the paper is infinitive (its a roll paper).
What and how I do it, that the report it will be printed out?
The report is filled up with all the data needed, and the code already gets the printer name, ... so what now?
- How to get the paper width and print the report (the report was made that all goes onto such paper width)?
- And that the printer will stop puting the paper out the it when the report is printed?
This code I have now, and I didnt test it yet, so I am not sure if it will work:
string printerName = GetPrinterName();
if (printerName != null)
{
cr.PrintOptions.PaperSource = PaperSource.Auto;
cr.PrintOptions.PaperSize = PaperSize.DefaultPaperSize;
CrystalDecisions.Shared.PageMargins edges = new CrystalDecisions.Shared.PageMargins(1, 1, 1, 1);
cr.PrintOptions.ApplyPageMargins(edges);
crystalReportViewer1.ReportSource = cr;
crystalReportViewer1.Refresh();
cr.PrintOptions.PrinterName = printerName;
cr.PrintToPrinter(1, false, 0, 0);
}
string[] sections = line.Split(new char[] {"><"}, StringSplitOptions.RemoveEmptyEntries);
I would like to create a simple program, like a game, but so far without any graphical interface. Only a code, supported with some numbers, so that the user will know whats going on in the background.
I was thinking of creating a racing game (like formula 1 or sometihng similar), with available data (attributes) like:
Driver: age, agility, concentration, experiance, stamina,...
Car: engine, chassis, tyres
Race: weather conditions
I would like to do a code which would simulate the race depending on the attributes I have.
Is there anytihng to start with, any similar examples, any directieves?
I would not like to complicate on the beginning, and any help would be really much appreciated.
An example for login form:
namespace LoginForm.cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strUserName = textBoxUserName.Text.Trim();
string strPassword = textBoxPassword.Text.Trim();
DAL setting = new DAL();
setting.UserName = strUserName;
setting.Password = strPassword;
if (!String.IsNullOrEmpty(strUserName) && !String.IsNullOrEmpty(strPassword))
{
bool UserValidated = setting.UserAuthorization();
if (UserValidated)
this.DialogResult = DialogResult.OK;
else
this.DialogResult = DialogResult.Cancel;
}
}
}
}
namespace LoginForm.cs
{
abstract class GetSet
{
protected string userName;
public string UserName
{
get { return userName; }
set { userName = value; }
}
protected string password;
public string Password
{
get { return password; }
set { password = value; }
}
public abstract bool UserAuthorization();
}
}
namespace LoginForm.cs
{
class DAL : GetSet
{
static string p = ConfigurationManager.ConnectionStrings["povezava"].ConnectionString;
public override bool UserAuthorization()
{
using (SqlConnection povezava = new SqlConnection(p))
{
using (SqlCommand cmd = new SqlCommand("Login_Search", povezava))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@strUsername", SqlDbType.VarChar, 50).Value = UserName;
cmd.Parameters.Add("@strPasswordInsert", SqlDbType.VarChar, 50).Value = Password;
try
{
string strPassword = null;
cmd.Connection.Open();
object objPassword = cmd.ExecuteScalar();
if (objPassword != null)
{
strPassword = Convert.ToString(objPassword);
return true;
}
else return false;
}
catch
{
return false;
}
finally
{
if (povezava.State == ConnectionState.Open)
cmd.Connection.Close();
}
}
}
}
}
}
try with override.
Still unclear...
Where exactly do you have all those values now?
Because what shows ur 1st post it is not possible (or pointless) to have all those values in a textBox.
Please clarify it a bit more, from where to where and what exactly would you like to transfer?
The error is simple: "Missing parameter values".
Dont`t worry about marking as salved. It`s not my 1st time here.
btw, can someone give me a shot explanation. What`s the difference between PrintDialog and cr1.PrintToPrinter?
Becuase with both of them I can seperately do printing. I mean its not necessary to use them both.
And finaly what do u suggest to use in general?
Now I use only this part of the code:
crystalReportViewer1.ReportSource = cr1;
crystalReportViewer1.PrintReport();
cr1.Refresh();
I am doing a crystal report with printing. I have encountered on this problem:
try
{
PrintDialog print = new PrintDialog();
print.ShowDialog();
crystalReportViewer1.ReportSource = cr1;
crystalReportViewer1.PrintReport();
cr1.Refresh();
cr1.PrintToPrinter(1, true, 1, 1);
}
catch
{
//MessageBox.Show("Some error occured...", "Opozorilo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I got an error on last line of the code (print to printer).
What am I misisng here?
Yes, I did as you told me and it works. Bit thx mate.
Question answered.
best regards.
Mitja
I was more thinking about this:
string myQuery =
"SELECT StudentName FROM Students WHERE " +
"where (month(birth) * 100) + day(birth) between " +
"(month(@monthFrom) * 100) + day(@dayFrom) and " +
"(month(@monthTo) * 100) + day(@dayTo)";
What do you thing?
This is my whole method:
private DataTable GetStudents(DateTime DateFrom, DateTime DateTo)
{
int MonthFrom = DateFrom.Month;
int MonthTo = DateTo.Month;
int DayFrom = DateFrom.Day;
int DayTo = DateTo.Day;
DataTable table = new DataTable("SelectedStudents");
string TimeSearching = "SELECT StudentName, Birth FROM Students WHERE " +
"MONTH(Birth) BETWEEN @MonthFrom AND @MonthTo AND " +
"DAY Birth) BETWEEN @DayFrom AND @DayTo";
SqlCommand cmd = new SqlCommand(TimeSearching, sqlConn);
cmd.Parameters.Add("@MonthFrom", SqlDbType.Int).Value = MonthFrom;
cmd.Parameters.Add("@MonthTo", SqlDbType.Int).Value = MonthTo;
cmd.Parameters.Add("@DayFrom", SqlDbType.Int).Value = DayFrom;
cmd.Parameters.Add("@DayTo", SqlDbType.Int).Value = DayTo;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
return table;
}
There is no errors at all just the dataTable is empty. If I exclude the Day the dataTable gets populated.
I would like to know why sql query for month and year is working, and is not working for day:
string myQuery = "SELECT StudentName FROM Students WHERE " +
"YEAR(Birth) BETWEEN @yearFrom AND @yearTo AND " +
"MONTH(Birth) BETWEEN @monthFrom AND @monthTo AND " +
"DAY(Birth) BETWEEN @dayFrom AND @dayTo;
As said, for year and month query works fine, but it doesn`t work for day. Why is that so?
Thats what I want to do. I would like to create a procedure from that upper querry.
But I do not know how to do it.
Here I`d need some help.
The code bellow is a sql querry, made in code. I would like to know how to do such stored procedure:
string[] NameSeperated = FullName.Split(' ');
string querryName = @"SELECT StudentID FROM Students WHERE Name = @name";
if (NameSeperated.Length > 1)
querryName += " AND LastName = @lastName";
using (SqlCommand cmd = new SqlCommand(querryName, sqlConn))
{
cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = NameSeperated[0].Trim();
if (NameSeperated.Length == 2)
cmd.Parameters.Add("@lastName", SqlDbType.VarChar, 50).Value = NameSeperated[1].Trim();
else if (NameSeperated.Length == 3)
cmd.Parameters.Add("@lastName", SqlDbType.VarChar, 50).Value = NameSeperated[1].Trim() + " " + NameSeperated[2].Trim();
}
ParameterFields paramFields = new ParameterFields();
ParameterField pfItem = new ParameterField();
pfItem.ParameterFieldName = "myParam"; //my parameter name which I created
ParameterDiscreteValue dcItem;
foreach (DataRow dr in PodatkiIzBlagajne.Rows)
{
dcItem = new ParameterDiscreteValue();
dcItem.Value = dr[0].ToString();
pfItem.CurrentValues.Add(dcItem);
paramFields.Add(pfItem);
}
The problem I see here is that there is no connection with the myParam and this code. How to connect it?
The only way when connection works is when I pass only 1 value like:
CrystalReport cr = new CrystalReport();
cr.SetParameterValue("myParam", myValue); //myValue is a string
But I would like to pass more then just one values to only one poarameter. So how to establish a connection between the parameter and the values?
Please!
I am back to my old problem... with passing multiple values into one parameter.
I still haven`t figured it out how to do the correct code for formula field.
How to do the formula in case if I have "n" values to pass to parameter?
I would really appreciate some help. I am really struggling now. please
Mitja
I would like to know how to pass object array (object[]) between classes with the code bellow, which now sends string only:
public delegate void MessageDelegate(Object sender, MessageEventArgs e);
public class MessageEventArgs : EventArgs
{
public string Message;
public MessageEventArgs(string msg)
{
this.Message = msg;
}
}
public interface IController
{
event MessageDelegate ControllerEvent;
void InvokeControllerEvent(string msg);
}
public class Controller : IController
{
public event MessageDelegate ControllerEvent;
public void InvokeControllerEvent(string msg)
{
this.OnControllerEvent(new MessageEventArgs(msg));
}
protected virtual void OnControllerEvent(MessageEventArgs mea)
{
if (this.ControllerEvent != null)
{
this.ControllerEvent.Invoke(this, mea);
}
}
}
I would like to know how to send a sms (text message) from windows application to a mobile phone (with entering the number) - for free.
One and the only option I know (and I tried) is to send it using email.
But I do not have any provider in my country to support this future. So the only thing that I am left with is to pay a service, like www.smsmail.com.
Does anyone have any idea of sometihng else how to send sms from pc (windows, windows application)?
I would like to know how to programmatically call a mathod regarding on time. In my example I would like to call a method every hour.
Can I use a Timer or is there something else?
How to put an image (BitMap) into a statusBar?
I was trying with:
1.
statusBar1.Text = Properties.Resources.MyPucture;
2.
Bitmap myPic = new Bitmap(Properties.Resources.MyPucture);
MethodToShowStatusBarImage()
{
statusBar1.Text = myPic;
}
but it is not working. Any clues how to salve this issue?
And besides, I have found a lot of example does with BitMapImage control, but I don`t know how to get it. I mean I can`t reach it, becuase I do know have the right reference (System.Windows.Media.Imaging - I can not find it between all those references, anyone know how to get it?).
I am using VS 2008 on Win 7.
Maybe is the problem I do not have installed .NET FrameWork 3.0, and I can not install it. Win 7 doesnt let me.
When I try to install it it throws a message that I have to turn it on in Control Panel/Programs/Turn Windows Features On/off.
And there I can not find .net FrameWork 3.0.
I would like to know how can I transfter a string value (a name or something) from Login class over static class to Form1?
This code I have:
1. In program class:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (LoginForm login = new LoginForm())
{
if (login.ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
}
}
}
2. In Login class, which checkes if the user has entered the correct user name and password (but here is no login code)
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
string strUserName = textBox1.Text;
string strPassword = textBox2.Text;
bool LoginSucceeded = CheckingLogin(strUserName, strPassword);
if (LoginSucceeded)
{
//Here I would need to pass "strUserName" to Form1
this.DialogResult = DialogResult.OK;
}
}
}
I would like to know how to pass the "strUserName from LoginForm to Form1, where I would like to show, who is logged in.
I have added some code, and it works, but its not th best solution I would say... its a bit complicated.
What do you think?
bool isUnckecked;
bool whenUnckecked;
bool isChecking;
bool canCheck;
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (!listView1.GetItemAt(e.X, e.Y).Checked)
{
canCheck = true;
listView1.GetItemAt(e.X, e.Y).Checked = true;
}
else
isUnchecked = true;
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (isUnchecked)
{
isUnckecked = false;
isChecking = true;
listView1.Items[e.Index].Checked = false;
e.NewValue = CheckState.Unchecked;
//MY NEW CODE FOR WHEN THERE IS NO ITEM CHECKED!!
isChecking = false;
whenUnckecked = true;
}
if (!isChecking && canCheck)
{
isChecking = true;
foreach (ListViewItem item in listView1.Items)
{
item.Checked = false;
}
listView1.Items[e.Index].Checked = true;
e.NewValue = CheckState.Checked;
canCheck = false;
isChecking = false;
}
else
{
if (isChecking || whenUnckecked)
{
e.NewValue = CheckState.Unchecked;
whenUnckecked = false;
}
else
{
e.NewValue = e.CurrentValue;
//Now I have a method here, when the new tick is checked!
}
}
}
The code bellow allow to select only item in a listView. That means there is only one tick in the listView - always.
But I would like to change the code bellow that will allow to unselect too, that there will be no tick at all.
So, no tick in the listView, or only one.
This is the code I would like to change. And I can not succeed it.
bool isChecking;
bool canCheck;
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (!listView1.GetItemAt(e.X, e.Y).Checked)
{
canCheck = true;
listView1.GetItemAt(e.X, e.Y).Checked = true;
}
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!isChecking && canCheck)
{
isChecking = true;
foreach (ListViewItem item in listView1.Items)
{
item.Checked = false;
}
listView1.Items[e.Index].Checked = true;
e.NewValue = CheckState.Checked;
canCheck = false;
isChecking = false;
}
else
{
if (isChecking)
{
e.NewValue = CheckState.Unchecked;
}
else
{
e.NewValue = e.CurrentValue;
//Now I have a method here, when the new tick is checked!
}
}
}
I am doing an application which has some calculation code. I would like to know if there is possible to remember the number from the previous event handler?
Lets say that I put into textbox1 number 10 and into textBox2 number 5.
When the even button1_Pressed starts the code has to sum these two number up.
In case if I press the same button again and I did not change any number in those two textBoxes, the code MUST NOT sum those numbers again.
How to achive this? It has to remember the values from the previous even somehow, that I can check the values in textBoxes from before and now.
And if there is no changes do not do the calculation, but if the numbers are different (just one of them, pr both) do the calculation.
I would like to know if there is any other way to create a doc (or txt) file, then this way that I have in my code:
if (!System.IO.Directory.Exists(System.IO.Path.GetTempPath() + @"TestDirectory"))
System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"TestDirectory");
string LogDatoteke = System.IO.Path.GetTempPath() + @"TestDirectory\TestFile.doc";
StreamWriter zapis;
zapis = File.CreateText(LogDatoteke);
zapis.WriteLine("Some text 1");
zapis.WriteLine("");
zapis.WriteLine("Some text 2");
zapis.WriteLine("Some text 3");
zapis.WriteLine("What ever");
zapis.Flush();
zapis.Close();
I would like to do a payment order, this one with crystal report:
I have already created something, but I do not have the exact lenght and width, like the original payment order has it.
I would like to know how to do get the exact measurments in the report as the origianal has (to do a custom paper size)?
Becuase I would like to print this payment orders one after another (they are holding together).
This is my code I have :
Form1:
private void buttonPrintSelected(object sender, EventArgs e)
{
for (int j = 0; j < listView1.Items.Count; j++)
{
if (listView1.Items[j].Checked == true)
{
string CustomerName = null;
CustomerName = listView1.Items[j].SubItems[1].Text;
DataSet ds = new DataSet();
//then I fill the dataSet with all the values I need in the report
Form2 form2 = new Form2();
form2.ds_form2 = ds; // I send the dataSet to Form2
form2.Show();
form2.Close(); //ADDED: IF I USE THIS LINE, THE REPORT IS NOT SHOWN WHEN CODE COMES BACK FROM THE form2
}
}
}
Form2:
public partial class Form2 : Form
{
public DataSet ds_Form2 { private get; set; }
CrystalReport3 cr3 = new CrystalReport3();
private void Form2_Load(object sender, EventArgs e)
{
foreach (DataRow dr in ds_Form2.Tables[0].Rows)
{
cr3.SetParameterValue("NameSurname", dr[0]);
//and all the other values bind to their parameters - this works ok
cr3.PrintOptions.PaperSize = PaperSize.PaperA4;
crystalReportViewer3.ReportSource = cr3;
crystalReportViewer3.Refresh();
cr3.PrintToPrinter(1, true, 0, 0); //THIS IS HOW I HAVE SET NOW - BUT IT IS NOT OK!
//Print the report. Set the no. of copies, collate (false or true), startPageN and endPageN . set startPageN and endPageN parameters to 0 to print all pages.
}
}
}
This code above is now showing every single customer selected from a listView. And is showing the print Dialog - cr3.PrintToPrinter shows that.
But I would like that PrintDialog is shown on the begining (only ones) and then the code prints out all the selected customers. Is there necessary …
I have a small problem with printing reports (made by crystal reports). In Form1 I have a list of customers in a ListView (with checkboxes).
If the users selects one customer (checkes ONE checkBox) the report is shown - and the report it self has on option to print.
If the user selects more then one, I do not want to show both reports, but only directly to print what is on both reports.
How to go into the Form2 class where the report is created, without calling form2.Show(); ?
From Form1 all the required values are gathered into DataSet, which is then passed to Form2 - for every single selected customer.
Would someone please help me some more with this issue? I can not figure it out by my self.
Please.
I finaly got sometihng useful written on some forum about passing multiple values to ONE parameter on report:
"In Crystal Reports, multiple-value and ranged-value parameters do not display all values entered into the parameter when the parameter is placed on a report. This occurs regardless of whether the parameter includes multiple discrete values, range values, or a combination of the two."
"To display all entries in a multiple-value parameter, create a formula to extract the parameter values and then concatenate them into a string."
So that means I can create just one formula field and put inside the formula which will get all the values and convert them to string.
I was thinking something of:
if UBound ({?Data}) = 1 then {?Data}[1]
else if UBound ({?Data}) = 2 then {?Data}[2]
else if UBound ({?Data}) = 3 then {?Data}[3]
Else if its not a good option, becuase it will look only one if. I need something else.
But it is showing only the 1st value always. I know you were saying I can create as many formula fields as many values I have, but by my logic, there can be only one as well. I just need the correct formula. Don`t you thing?
But even if I need to have 3 formula fileds in this my example would be ok, just it does not work jet correctly.
Shouldnt I use the "join"?