Sei sulla pagina 1di 5

PostedByLahaulSeth

AftertestingoutJavaforacoupleofweeks,thisweekendIdecidedtotryout.NET.I
amabigfanofwebapplicationsbutrecentlyIvetakenaninteresttowardsJavaand
WindowsFormsApplications.So,thefirstthingthatcametomyattentionwasthe
WindowsApplicationFormsinC#.

So,basicallyIveusedVisualStudio2012andfordatabaseIveusedEasyPHPDev
ServerbecauseMySQLismymostfavoritedatabase.

GUIDesign

ForGUIdesign,Ikeptitsimplesomepanels,labelsandtextboxesalongwith
buttons.

So,thatcaresofthesimpleGUI.

MySQLDatabaseConnection

BeforemakingtheMySQLdatabaseconnection,youneedtodownloadMySQL.NET
Connectorwhichyoucandownloadfromhere.Afterdownloadingtheconnectorforthe
.NETandMONOplatform,youneedtoextractit.Thenyouwillneedtoaddthesetwo
filesmysql.data.dllandmysql.web.dllasreferenceinyourproject.Thesetwofiles
arebasicallyADO.NETMySQLDriver.

Aftertheadditionofthesetworeferencesyoucanwritethecode.Themostimportant
functioninLoginisthatoftheSubmitbutton.So,heresthesimplecodethatIused.

1 usingSystem
2 usingSystem.Collections.Generic
3 usingSystem.ComponentModel
4 usingSystem.Data
5 usingSystem.Drawing
6 usingSystem.Linq
7 usingSystem.Text
8
usingSystem.Threading.Tasks
9
usingSystem.Windows.Forms
10
usingMySql.Data.MySqlClient//requiredforMySQLconnectionafteradditionofMyS
11

12
namespaceApplicationDemo
13
{
14
publicpartialclassForm1:Form
15
{
16
privatestringconn
17
privateMySqlConnectionconnect
18
publicForm1()
19
{
20
InitializeComponent()
21
22 }
23
24 privatevoiddb_connection()
25 {
26 try
27 {
28 conn="Server=localhostDatabase=netdemoUid=rootPwd="
29 connect=newMySqlConnection(
30 connect.Open()
31 }
32 catch(MySqlExceptione)
33 {
34 throw
35 }
36 }
37
38 privateboolvalidate_login(stringuser
39 {
40 db_connection()
41 MySqlCommandcmd=newMySqlCommand
42
cmd.CommandText="Select*fromloginwhereusername=@userandpassword
43
cmd.Parameters.AddWithValue("@user"
44
cmd.Parameters.AddWithValue("@pass"
45
cmd.Connection=connect
46
MySqlDataReaderlogin=cmd.ExecuteReader
47
if(login.Read())
48
{
49
connect.Close()
50
returntrue
51
}
52
else
53
{
54
connect.Close()
55
returnfalse
56
}
57
}
58

59
privatevoidsubmit_Click(objectsender
60
{
61
stringuser=username.Text
62
stringpass=password.Text
63
64 if(user==""||pass=="")
65 {
66 MessageBox.Show("EmptyFieldsDetected!Pleasefillupallthefiel
67 return
68 }
69 boolr=validate_login(user,pass
70 if(r)
71 MessageBox.Show("CorrectLoginCredentials"
72 else
73 MessageBox.Show("IncorrectLoginCredentials"
74 }
}
}

SofromabovethenameoftheMySQLdatabaseisnetdemoandthenameofthe
tableislogin.

ValidationandOutput

Foralittleaddedsecurity,Iveaddedavalidationparameter.Ifbothoroneofthe
textboxisemptywhilesubmittingtheform,itwilldisplayaerrormessageliketheone
below.

Forthecorrectusernameandpassword,itwillshowamessageboxofCorrectLogin
CredentialsandforanincorrectcomboitwilldisplayamessageboxofIncorrect
LoginCredentials.

Potrebbero piacerti anche