» »

razložitev nekaterij elementov v visual studio 05

razložitev nekaterij elementov v visual studio 05

nody ::

lahko kdo natančno razloži, zakaj se uporabljajo elementi v visual studio ...kaj služijo....oleDbCommand1, oleDbConnection1, oleDbDataAdapter1, kaj je namen oziroma njihova uporaba..rad bi da kdo to razloži, če zna, brez uporabe kakih linkov v angleščini...:):) hvala že vnaprej...

morbo ::

OK. Najprej opozorilo: V Visual Studiu sem približno tak začetnik kot ti (ok, v VS6 sem se včasih neki zajebaval z basicom), ampak tale primer dela in upam da ti bo vsaj osnovno razložil zadeve.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Test {

public partial class Obrazec : Form {

private OleDbConnection povezava;
private string conString = @"Provider=Microsoft.JET.OLEDB.4.0;"
+ @"data source=C:\mojaPotDoBaze.mdb;";

private void poseliTabelo() {
// povezavo ustvarimo tako da predmetu podamo niz s podatki
povezava = new OleDbConnection(conString);
try {
povezava.Open();
// ustvarimo novo poizvedbo na podlagi povezave
OleDbCommand poizvedba = new OleDbCommand("SELECT * FROM uporabniki", povezava);
// s pomočjo poizvedbe ustvarimo adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(poizvedba);
// ustvarimo navidezno (ne-grafično) tabelo
DataTable dt = new DataTable();
// z adapterjem zapolnimo navidezno tabelo s podatki
adapter.Fill(dt);
// tabeli (ki je predmet DataGridWiev, poprej postavljen na obrazec) dodelimo izvor podatkov
tabela.DataSource = dt;
// zapremo povezavo
povezava.Close();

} catch (Exception e) { MessageBox.Show(e.Message); }
}
}
}


OleDbConnection je predmet ki predstavlja povezavo z bazo. Povezavo ustvarimo s pomočjo niza (conString), v katerega zapišemo podatke o gonilniku, lokaciji baze, uporabniškem imenu, geslu... OleDbCommand predstavlja SQL ukaze, ki jih vršimo nad tabelami v bazi - SELECT, INSERT, UPDATE... OleDbDataAdapter je povezovalec prejšnjih dveh, s katerim polnimo predmete ki lahko prejmejo podatke v tej obliki (DataTable, DataSet...). Te predmete potem dodelimo "končnim gradnikom", kot vire podatkov. Operacije ki jih potem izvajaš nad viri podatkov (DataTable v zgornjem primeru) se odražajo v gradnikih s katerimi so povezani. :))

PS. Po tistih enkah sklepam da si na form naflikal en kup grafičnih predmetov in potem nič jasno... ne, ne in ne! Če se hočeš kaj navadit najprej vzami beležko in programe piši na roko. Orodja za hiter razvoj so nepogrešljiva, ampak šele ko veš kaj packajo namesto tebe v ozadju oz. takrat ko obvladaš osnove. Začetnike en tak IDE kot je Visual Studio zmede v nulo...

PPS. Brez uporabe linkov v angleščini bo šlo težko...

EDIT: zadeva se poveže z bazo v Access-u

Zgodovina sprememb…

  • spremenil: morbo ()

nody ::

tnx....tudi kaj v angleščini pride prav....hehe...lp...hvala...0:)

nody ::

lep pozdrav zanima me, ali lahko kdo skomentira to kodo :
#endregion

#region Methods for New, Save, Delete, Edit, Refresh, Exit


private void fnGetLastPersonID()
{
/*------------------------------------------------------------------------
* Implemented: 8.12.2004
* Purpose:
* I implemented this method because of the AutoNumber.
* create the select command only for the PersonID column
* run the while-loop and get the all values(contents) of the
* column 0(GetValue(0)), store it in a object variable, convert it
* to integer until the end of the column(0) values.
* if the while-loop is finished then you get the last value
* in the first column(0) GetValue(0)
* outside while-loop, increment the PersonID by 1
* and display it in the TextBox
*------------------------------------------------------------------------------*/
//get the correct value for the last inserted identity value with Max(PersonID)
string strCom = "Select Max(PersonID) from PersonTable" ;
OleDbCommand cmd =new OleDbCommand(strCom,this.oleDbConnection1);

OleDbDataReader reader;
//Execute the command and get the DataReader
reader =cmd.ExecuteReader() ;
int i=0 ; //how many records in the table?, only for test
int iPersonid=0; //the integer value of the first column(0) contents
//loop
while(reader.Read())
{
i++ ;
//GetValue(0) means: The contents of the first column(0)(PersonID) in the table
object obValue = reader.GetValue(0);
iPersonid = Convert.ToInt32(obValue.ToString());
}
//loop is finished: so the last int value of the first column(0) is now in iPersonid
i++ ;
this.textboxPersonID.Text=iPersonid.ToString(); //display it in TextBox
reader.Close(); //close the DataReader otherwise error
MessageBox.Show("Record with new PersonID: "+iPersonid.ToString()+" inserted successfully","Save New",MessageBoxButtons.OK,MessageBoxIcon.Information); //inform the user
}


private void fnEnableToolbarButtons(bool b, string s1)
{
if (s1=="New")
this.toolBarButtonNew.Enabled=b;
else if (s1=="Save")
this.toolBarButtonSave.Enabled=b;
else if (s1=="Delete")
this.toolBarButtonDelete.Enabled=b;
else if (s1=="Edit")
this.toolBarButtonEdit.Enabled=b;
else if (s1=="Refresh")
this.toolBarButtonRefresh.Enabled=b;
}

public void fnEnableButtonsNextPreviousLastFirst(bool flag)
{
string str;
foreach(Control ctrl in this.Controls)
{
str = Convert.ToString(ctrl.GetType());
if(str == "System.Windows.Forms.Button")
{
ctrl.Enabled = flag;
}//if
}//for
}


private void fnSaveNewRecord()
{
try
{
string strInsert;

strInsert = "insert into PersonTable(FirstName, LastName, Title, City,Country)"
+ " values('" + this.textboxFirstname.Text + "', '"
+ this.textboxLastname.Text + "', '"
+ this.textboxTitle.Text + "', '"
+ this.textboxCity.Text + "', '"
+ this.textboxCountry.Text + "')";

if (this.textboxFirstname.Text !="" && this.textboxLastname.Text !=""&& this.textboxTitle.Text !="" && this.textboxCity.Text !="" && this.textboxCountry.Text !="")
{
this.oleDbDataAdapter1.InsertCommand.CommandText = strInsert;
//do the insert
this.oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
//Get the last PersonID from the table and display it in TextBox
fnGetLastPersonID();
fnEnableButtonsNextPreviousLastFirst(true);
fnEnableToolbarButtons(true, "Edit");
fnEnableToolbarButtons(true, "Delete");
fnEnableToolbarButtons(false, "Save");
this.fnEnableDisableTextBox(false);
}
else
{
MessageBox.Show("You have to fill the TextBoxes...","WARNING", MessageBoxButtons.OK,MessageBoxIcon.Warning);
this.textboxFirstname.Focus();
}//else
}
catch (Exception ex)
{
MessageBox.Show("Error in inserting new record : "+ex.Message,"Insert Error",MessageBoxButtons.OK,MessageBoxIcon.Information);
fnRefreshDataSet();
} //try-catch
}


private void fnDeleteCurrentRecord()
{
DialogResult dr=MessageBox.Show("Are you sure you want to delete this record ? ", "Confirm deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
//convert textboxPersonID into integer
int pid=int.Parse(this.textboxPersonID.Text);
if (dr ==DialogResult.Yes)
{
string strDel="DELETE FROM PersonTable WHERE PersonID= "+pid;
try
{
fnExecuteQuery(strDel);
}
catch(Exception ex)
{
MessageBox.Show("Error in deleting : "+ex.Message);
return;
}
fnRefreshDataSet();
MessageBox.Show("Record deleted...");
}
else
MessageBox.Show("Record NOT deleted...");
}

private void fnSetEditUpdateText(string str)
{
this.toolBarButtonEdit.Text=str;
}


public void fnUpdateRecord()
{
try
{
string strUpdateQuery = "update PersonTable set FirstName='"
+this.textboxFirstname.Text+"',LastName='"
+this.textboxLastname.Text+"' ,Title='"
+this.textboxTitle.Text+"' ,City='"
+this.textboxCity.Text+"' ,Country='"
+this.textboxCountry.Text +"' WHERE PersonID= "+this.textboxPersonID.Text;
fnExecuteQuery(strUpdateQuery);
fnRefreshDataSet();
MessageBox.Show("Record updated...");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
} //try-catch
}


private void fnExecuteQuery(string strQuery)
{
try
{
this.oleDbCommand1=new OleDbCommand(strQuery,this.oleDbConnection1);
this.oleDbCommand1.CommandType=CommandType.Text;
this.oleDbCommand1.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}//try-catch
}


private void fnRefreshDataSet()
{
this.dataSet11.Clear(); //clear the contents of dataset
this.oleDbDataAdapter1.Fill(this.dataSet11,"PersonTable");
}


private void fnExit()
{
//ask user before quit
ExitClass ec=new ExitClass();
ec.fnExitUniversal();
}

private void fnClearAllTextBox()
{
/* ------------------------------------------------
* it runs through all the TextBox and clears them
* -----------------------------------------------*/
string str;
foreach(Control ctrl in this.Controls)
{
str = Convert.ToString(ctrl.GetType());
if(str == "System.Windows.Forms.TextBox")
{
ctrl.Text = "";
}//if
}//for
}

public void fnEnableDisableTextBox(bool flag)
{
/* -----------------------------------------------------------------------------
* it runs through all the TextBox and enables/disables them depending on flag
* ---------------------------------------------------------------------------*/
string str;
foreach(Control ctrl in this.Controls)
{
str = Convert.ToString(ctrl.GetType());
if(str == "System.Windows.Forms.TextBox")
{
ctrl.Enabled = flag;
}//if
}//for
}

#endregion

//----------------------------------------------------------------------

private void cPersonalAddres_Load(object sender, System.EventArgs e)
{
fnGetDataConnection(); //Connection to the database
fnShowAllRecordsInTextbox(this.dataSet11);
this.bindManager=this.BindingContext[this.dataSet11, "PersonTable"];
fnDisplayStatusbarText("First");
fnEnableDisableTextBox(false);
}


#region Navigation buttons Next, Previous, First, Last
private void btNext_Click(object sender, System.EventArgs e)
{
if (this.bindManager.Position < this.bindManager.Count-1)
{
this.bindManager.Position +=1; //increment position by 1
fnDisplayStatusbarText(""); //clear the Statusbar
}//if
else
{
fnDisplayStatusbarText("End Of Records...");
}//else
}

private void btPrevious_Click(object sender, System.EventArgs e)
{
if((bindManager!=null)&(bindManager.Count>0)&(bindManager.Position>0))
{
this.bindManager.Position -=1; //move to the previous record
fnDisplayStatusbarText(""); //display record number
}
else
{
fnDisplayStatusbarText("Beginning Of Records...");
}
}

private void btFirst_Click(object sender, System.EventArgs e)
{
this.bindManager.Position=0; //first record number=0
fnRefreshDataSet();
fnDisplayStatusbarText("First Record...");
}

private void btLast_Click(object sender, System.EventArgs e)
{
//get the number of all the records and assign to Position
this.bindManager.Position=this.bindManager.Count-1;
fnDisplayStatusbarText("Last Record...");
}

private void fnDisplayStatusbarText(string strText)
{
//get the current position of the record and display it in StatusBar
int nPos=this.bindManager.Position;
nPos++;
this.statusBar1.Text =" Record: "+nPos.ToString()+" of "+this.bindManager.Count.ToString()+" "+strText;
}


#endregion

#region DataConnection
public void fnGetDataConnection()
{
try
{
this.oleDbConnection1.Open();
//refreshes rows in the DataSet
this.oleDbDataAdapter1.Fill(this.dataSet11,"PersonTable");
}
catch(Exception ex)
{
MessageBox.Show("Error : "+ex.Message,"Connection Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit(); //finish the program
}//try-catch
}

#endregion

#region Databinding

private void fnShowAllRecordsInTextbox(DataSet ds)
{
//DataBinding for all TextBoxes
this.textboxPersonID.DataBindings.Add("Text",ds, "PersonTable.PersonID");
this.textboxFirstname.DataBindings.Add("Text",ds, "PersonTable.FirstName");
this.textboxLastname.DataBindings.Add("Text", ds, "PersonTable.LastName");
this.textboxTitle.DataBindings.Add("Text", ds, "PersonTable.Title");
this.textboxCity.DataBindings.Add("Text", ds, "PersonTable.City");
this.textboxCountry.DataBindings.Add("Text", ds, "PersonTable.Country");
}

#endregion

#region MenuItems
private void miExit_Click(object sender, System.EventArgs e)
{
//call the method fnExit()
fnExit();
}

private void miAbout_Click(object sender, System.EventArgs e)
{
//show the about form
FormAbout fa=new FormAbout();
fa.ShowDialog();
}
#endregion
}
}
********************************************************************************************************************************************************

je to koda, ki jo je potrebno vso vpisati, ali se del le te sam generira ob dodajanju kakih elementov ipd.....

********************************************************************************************************************************************************

zanima me še, kje se določi pot do baze v accessu, imam aplikacijo, ki vedno potrebuje podatke z baze, če le te baze ni na disku C: mapa\ ni možno sploh opravljati z aplikacijo....zanima me še, ali se da to nastaviti, npr, da bi pot nastavil v mapi,kjer se nahaja celotna aplikacija...
kako je s setupom, če želiš, da bi ti aplikaicja brala z accesove baze, je sploh možno narediti setup, ki vsebuje access bazo, ....tnx že vnaprej...

morbo ::

System.Windows.Forms.Application.StartupPath ti vrne imenik kjer se trenutno izvaja .exe, tako da .mdb kopiraj zraven. Setupa pa ne rabiš - ko buildaš zadevo je vse kar potrebuješ v mapi "pot do programa\bin\release". Uni špeh pa je izdatno komentiran, tako da se potrudi.

nody ::

zanima me, kje se definira pot do baze, s katere Aplikacija bere ... jaz imam na aplikaicji, ki sem jo dobil, narejeno, da mora biti baza nastanjena v C:\mapa\data\ ...kje se to spremeni lp tnx že vnaprej..

morbo ::

Pot do baze definiraš tam kjer ustvarjaš Connection predmet - to bo najbrž kak obrazec, ali razred kjer imaš statično metodo main. Kje se to nahaja v tvojem primeru pa nimam pojma... uporabi search... Ti pa predlagam da zadevo raje spišeš sam iz nule, namesto da copy-pastaš primere iz interneta - tako boš vsaj vedel kje, kako in kaj....

darkolord ::

V app.config to shraniš


Vredno ogleda ...

TemaSporočilaOglediZadnje sporočilo
TemaSporočilaOglediZadnje sporočilo
»

C# težava

Oddelek: Programiranje
233744 (2590) mladec
»

[C#] Delo z okni - urejanje osebe

Oddelek: Programiranje
8988 (860) darkolord
»

c# class

Oddelek: Programiranje
342271 (1865) japol
»

C# okna in podokna

Oddelek: Programiranje
111658 (1252) FlashM
»

VC# insert into oledb ne deluje

Oddelek: Programiranje
191639 (1410) Good Guy

Več podobnih tem