|
|
Tricky with an array, but for a List<T> you can use an extension method:
public static class StringAndIntExtensions
{
public static void Add(this ICollection<StringAndInt> list, string myString, int myInt)
{
list.Add(new StringAndInt(myString, myInt));
}
} to let you write:
var myList = new List<StringAndInt>
{
{ "String", 0 },
{ "String", 1 },
{ "String", 2 }
}; The Magical Methods in C# · Cezary Piątek Blog[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: Tricky with an array, but for a List<T> you can use an extension method: Not really tricky: Couldn't you just add .ToArray() on the end?
But, I admit that I concur with the original questioner. There have been many times when I would have liked to have used exactly the same syntax as suggested in the question. There is no doubt that the current method is clunky. As was stated, even plain C has been able to do it for donkey's years. It would also be nice to have initialiser expressions in assignments and as function parameters as well as in initialisations without explicit new type at the beginning.
|
|
|
|
|
Dictionary<string, int> dic = new Dictionary<string, int>() { { "AAA", 1 }, { "BBB", 2 }, { "CCC", 3 } };
KeyValuePair<string, int>[] array = dic.ToArray();
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
I'd use Tuples:
private List<(string str, int i)> TPLs = new List<(string , int)>
{
("hello", 0), ("goodbye", 1)
};
var item0 = TPLs[0];
string str = item0.str;
int igr = item0.i;
var index1 = TPLs.IndexOf(("goodbye", 1));
TPLs.Add((str: "whatever", i: 6)); There is an OrderedDictionary Class that allows access by key or index: [^]
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
modified 28-Jul-20 2:35am.
|
|
|
|
|
Is there are way to covert Visual C++ 2005 project to 2016?
|
|
|
|
|
|
Why have you posted a question about C++ in the C# forum? They are completely different languages.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
public class ConnectionDB
{
public OleDbConnection sql_con;
public void CONNECTER()
{
try
{
string connetionString = null;
connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\DB_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
sql_con = new OleDbConnection(connetionString);
sql_con.Open();
}
catch (Exception ex)
{
MessageBox.Show("Erreur de connexion à la base donnée" + ex.ToString());
}
}
public void DECONNECTER()
{
try
{
if (sql_con.State == ConnectionState.Open)
{
sql_con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Erreur de deconnexion à la base donnée" + ex.ToString());
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ConnectionDB d = new ConnectionDB();
using (OleDbCommand cmbox = d.sql_con.CreateCommand())
{
cmbox.CommandText = "SELECT Code_article FROM Catalogue";
d.sql_con.Open();
d.DR = cmbox.ExecuteReader();
try
{
while (d.DR.Read())
{
CmbRef_Produit.Items.Add(d.DR["Code_article"]).ToString();
}
if (string.IsNullOrWhiteSpace(CmbRef_Produit.Text ))
{
Lbl_affich_TxtQteStock.Text = "";
Lbl_Affich_Designation.Text = "";
Lbl_Affich_PrixUnitaire.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
d.sql_con.Close();
}
}
}
}
Quote: I created a ConnectionDB class and 2 CONNECT and DISCONNECT methods.
I needed to open the database so I called the CONNECT method but I have an error telling me that my database is still closed so I change to sql-con.open and it works.
So my question is: Why and what is the difference.
|
|
|
|
|
You need to show the code that uses the CONNECTER method.
|
|
|
|
|
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ConnectionDB d = new ConnectionDB();
using (OleDbCommand cmbox = d.sql_con.CreateCommand())
{
cmbox.CommandText = "SELECT Code_article FROM Catalogue";
d.CONNECTER();
d.DR = cmbox.ExecuteReader();
try
{
while (d.DR.Read())
{
CmbRef_Produit.Items.Add(d.DR["Code_article"]).ToString();
}
if (string.IsNullOrWhiteSpace(CmbRef_Produit.Text ))
{
Lbl_affich_TxtQteStock.Text = "";
Lbl_Affich_Designation.Text = "";
Lbl_Affich_PrixUnitaire.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
d.DECONNECTER();
}
}
}
}
|
|
|
|
|
I am not sure that the sequence of commands is correct. Try this:
using (ConnectionDB d = new ConnectionDB())
{
d.CONNECTER();
using (OleDbCommand cmbox = d.sql_con.CreateCommand())
{
cmbox.CommandText = "SELECT Code_article FROM Catalogue";
}
d.DECONNECTER();
}
|
|
|
|
|
Thanks i will try it and you will get back
|
|
|
|
|
I try and the error comes from me thank you very much mmister it works.
|
|
|
|
|
First off, don't hard code connection strings - they need to be in a config file or similar, if only so you don't release the password in clear text with your app...
Second, never store databases in your app directory: although it works in development, it will fail in production as the application folder rarely has write permissions anymore for anti-virus reasons. See here: Where should I store my data?[^] for some better ideas.
Thirdly, you are much, much better off creating your Connection object in your code when you need it inside a using block, as they are scarce resources and should be Disposed when you are finished with them:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
{
cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int age = (int) reader["Age"];
string desc = (string) reader["Description"];
Console.WriteLine($"{age}\n{desc}");
}
}
}
} That way, whatever happens to your code, the objects will be closed and disposed for you automatically.
Fourthly, although you are trying to separate the DB from the form (which is a good idea) don't use MessageBox to report problems with DB related stuff - it makes too many assumptions about how your code will be used. Error handling and reporting is the province of the Presentation Layer, not the Data Layer: there is no guarantee that the user will be able to see a MessageBox! Let the code that calls the DB stuff handle errors - it can report or not, but it may log instead, or just terminate what it is doing. Your way, the user gets the MessageBox, then your app crashes because the connection isn't open anyway.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
thank you sir message well received. I haven't tried the configuration file side for the connection to the database yet, but I will study it and see if I can manage it.
|
|
|
|
|
public class ConnectionDB
{
public OleDbConnection sql_con;
public OleDbCommand sql_cmd;
public OleDbDataAdapter DB;
public DataSet DS = new DataSet();
public DataTable DT = new DataTable();
public OleDbDataReader DR;
public string connetionString = null;
public void CONNECTER()
{
connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\DB_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
sql_con = new OleDbConnection(connetionString);
}
public void DECONNECTER()
{
if (sql_con.State == ConnectionState.Open)
{
sql_con.Close();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ConnectionDB d = new ConnectionDB();
private void LoadDB()
{
using (OleDbConnection sql_con = new OleDbConnection(d.connetionString))
{
sql_con.Open();
using (OleDbCommand sql_cmd = d.sql_con.CreateCommand())
{
string CommandText = "SELECT * FROM Detail_temp";
d.DB = new OleDbDataAdapter(CommandText, d.sql_con);
d.DS.Reset();
d.DB.Fill(d.DS);
d.DT = d.DS.Tables[0];
dataGridView1.DataSource = d.DT;
d.DECONNECTER();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
LoadDB();
d.sql_con.Open();
TxtQteCmd.Text = "1";
Lbl_Affich_TotalCmd.Text = "0";
LblAfficDate.Text = DateTime.Now.ToString();
using (OleDbCommand cmbox = d.sql_con.CreateCommand())
{
cmbox.CommandText = "SELECT Code_article FROM Catalogue";
using (d.DR = cmbox.ExecuteReader())
{
try
{
while (d.DR.Read())
{
CmbRef_Produit.Items.Add(d.DR["Code_article"]).ToString();
}
if (string.IsNullOrWhiteSpace(CmbRef_Produit.Text))
{
Lbl_affich_TxtQteStock.Text = "";
Lbl_Affich_Designation.Text = "";
Lbl_Affich_PrixUnitaire.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
d.DECONNECTER();
}
d.DECONNECTER();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Sir I tried to do as you suggested and I would like you to take a look at my code, just see if it's good. And I would also like to know if the DISCONNECT method is worth it
|
|
|
|
|
hello
I am seraching some infos to create ma own script language to execute and enhance dos command in relation with my application variable with for and if conditions.
if you have some exemple or informations ?
thx
didier
|
|
|
|
|
Your question is a word salad and really makes no sense.
Are you asking how to add scripting support to some other application you've written? Are you trying to add command line argument support to your app?
What do you mean by "enhance dos command"?
Perhaps if you gave an example of what you're trying to do...
|
|
|
|
|
Windows command shell (aka dos) language already contains FOR and IF commands.
|
|
|
|
|
In case you're not aware of ".bat" files. I'd say more than one command in a file constitutes a "script".
DOS Batch Files
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
|
I want a scritpt can interact with ma database and my own function .
thescript must interact with log4net for his operation
exemple
if movefile( <varfromdb("key1")>\too.txt , <varfromdb("key2")>\foo.txt) > 0 then
print ("Error")
endif
|
|
|
|
|
OK. You can forget the "DOS", as you called it, batch file.
Use Powershell if you want Log4Net support.
You can use Powershell to do anything you want from a command line, albeit a PowerShell prompt.
|
|
|
|
|
Yes but the power shell syntax is so harddy for a little user...
and it must work on server from 2k3 to 2k16 and the same in linux.
|
|
|
|