I'm trying to display name suggestions on a textbox but it's not suggesting anything. I followed a couple tutorials about this but still with the exact same code I cant make it work. I'm using Dapper so maybe I have done something wrong there. Am I missing something?
This is what I have done with Dapper:
public static List<string> DevolverNombres()
{
var dbCon = DBConnection.Instancia();
if (dbCon.Conectado())
{
using (IDbConnection conexion = dbCon.Conexion)
{
var output = conexion.Query($"SELECT nombre FROM usuario;").ToList();
var lista = new List<string>();
foreach (IDictionary<string, object> row in output)
{
foreach (var pair in row)
{
lista.Add(pair.Value.ToString());
}
}
return lista;
}
}
else return null;
}
And this is what I have in the form:
private void Home_Load(object sender, EventArgs e) {
var nombres = AccesoDatos.DevolverNombres();
var lista = new AutoCompleteStringCollection();
foreach(string elem in nombres)
{
lista.Add(elem);
}
txtBuscar.AutoCompleteCustomSource = lista;
}
Related
I am new to programming in C#
I want to read the csv file and update the fields in elastic search. I already have this function made by someone else and I want to call this function and update fields.
public static bool UpdateDocumentFields(dynamic updatedFields, IHit<ClientDocuments> metaData)
{
var settings = (SystemWideSettings)SystemSettings.Instance;
if (settings == null)
throw new SettingsNotFoundException("System settings have not been initialized.");
if (ElasticSearch.Connect(settings.ElasticAddressString(), null, out ElasticClient elasticClient, out string status))
{
return ElasticSearch.UpdateDocumentFields(updatedFields, metaData, elasticClient);
}
return false;
}
what I have done myself so far is :
private void btnToEs_Click(object sender, EventArgs e)
{
var manager = new StateOne.FileProcessing.DocumentManager.DocumentManager();
var path = "C:/Temp/MissingElasticSearchRecords.csv";
var lines = File.ReadLines(path);
foreach (string line in lines)
{
var item = ClientDocuments.GetClientDocumentFromFilename(line);
if (item != null)
{
var output = new List<ClientDocuments>();
manager.TryGetClientDocuments(item.AccountNumber.ToString(), 100, out output);
if (output!= null && output.Count <= 0)
{
var docs = new List<ClientDocuments>();
//var doc = docs.Add();
// var doc = docs.Add();
//docs.Add(doc);
foreach (var doc in output)
{
if (!item.FileExists)
{
//insert in elastic search
manager.UpdateDocumentFields(output, );
}
else
{
//ignore
}
}
My problem here is manager.updateDocumentFields() is a function. I am calling it but what I need to pass as a parameter? Thanks in advance.
I am using EPPlus to generate excel file with multiple sheets.I am trying to add multiple worksheet to a single excel file from different thread and getting ambiguous error message root level is invalid
Here is my code. please some one have look and tell me what i am doing wrong in my code ?
ExcelPackage excelPackage = null;
private void button1_Click(object sender, EventArgs e)
{
string exclpath = #"d:\Test1.xlsx";
FileInfo fi = new FileInfo(#exclpath);
excelPackage = new ExcelPackage(fi);
Action[] actions;
actions = new Action[]
{
() => Test1(),
() => Test2()
};
Parallel.Invoke(actions);
excelPackage.Save();
}
private void Test1()
{
OfficeOpenXml.ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("Delta");
ws.Cells[1, 1].Value = "Test Delta";
}
private void Test2()
{
OfficeOpenXml.ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("Horizontal");
ws.Cells[1, 1].Value = "Test Horizontal";
}
Please guide me how can i add multiple sheets with data from different thread into single excel file.
is it not possible ?
if possible please guide me. Thanks
I worked on similar requirement recently and the way I handled is given below,
Create a separate class to hold the results. As Each method produces different type of list object, I added a property of type IList.
public class SearchResult
{
public IList Result { get; set; }
}
Now, use parallel invoke to get results, create a separate instance of SearchResult class, set the response to Result property
private static void CreateReport(List<RawData> rawDataList)
{
var resultList = new List<SearchResult>();
Parallel.Invoke(
() =>
{
var result = new SearchResult();
result.Result = SearchStudent(rawDataList);
resultList.Add(result);
},
() =>
{
var result = new SearchResult();
result.Result = SearchStaff(rawDataList);
resultList.Add(result);
}
);
ExcelWriter.CreateReport(resultList);
}
Now you have a resultlist with different type of results. I want to add them in separate sheet and generate the excel file.
public static void CreateReport(List<SearchResult> searchResults)
{
using (var xlpackage = new ExcelPackage())
{
foreach(var searchResult in searchResults)
{
if (searchResult.Result?.Count == 0)
{
continue;
}
var resultType = searchResult.Result[0].GetType();
var worksheet = xlpackage.Workbook.Worksheets.Add(resultType.Name);
var columnNames = Helper.GetPropertiesNames(Activator.CreateInstance(resultType)).ToList();
int colNumber = 1;
foreach (var columnName in columnNames)
{
worksheet.Cells[1, colNumber++].Value = columnName;
}
int rowNumber = 1;
foreach (var data in searchResult.Result)
{
//fill the cells, format as per requirement
}
}
var fileName = "Demo.xlsx";
var fileInfo = new FileInfo(Path.Combine(Config.ReportLoc, fileName));
xlpackage.SaveAs(fileInfo);
}
}
I hope this helps/provides idea for your requirement.
I am using linq to query data.
But I want it return uppercase field.
Below is my code, how to transfer all field to uppercase?
public List<dynamic> QueryToList(string connStr, string sql)
{
using (OracleConnection conn = new OracleConnection(connStr))
{
conn.Open();
var results= conn.Query(sql).ToList();
conn.Close();
return results; //For now, it would return all fields into lower case.
}
}
Edit:
Thanks for #Alen.Toma, I use the code below and it return the result I want.
public List <dynamic> QueryToList(string connStr, string sql)
{
conn.Open();
var results = conn.Query(sql);
conn.Close();
var valueResult = new List<dynamic>();
foreach (dynamic item in results)
{
var dicItem = item as IDictionary<string, object>;
var x = new ExpandoObject();
foreach (var i in dicItem.Keys)
{
((ICollection<KeyValuePair<string, object>>)x).Add(new KeyValuePair<string, object>(i.ToUpper(), dicItem[i]));
}
valueResult.Add(x);
}
return valueResult;
}
Well I agree with #Panagiotis Kanavos, even better is to convert the data to an class object.
Incase you still want to do it as such
Here is an example.
public List <dynamic> QueryToList(string connStr, string sql) {
var valueResult = new List <dynamic> ();
using(OracleConnection conn = new OracleConnection(connStr)) {
conn.Open();
var results = conn.Query(sql).ToList();
conn.Close();
foreach(var item in results) {
var dicItem = item as Dictionary <string,object> ;
var x = new ExpandoObject();
forEach(var i in dicItem.Keys)
((ICollection<KeyValuePair <string, object>>)x).Add(i.ToUpper(), dicItem[i]);
valueResult.Add(x);
}
return valueResult;
}
}
I am new to programming and to this forum. I have searched the forum for answers but havent found anything that works for me. I have created a adressbook in WinForms with a search function. The search finds the the specified contact, but when I click on the contact the information it loads belongs to the first contact in the List. This happens for every contact in the list exept for the first contact.
var TempVar = People.Where(a => a.Namn.ToLower().Contains(txtSearchbar.Text.ToLower()) ||
a.PostOrt.ToLower().Contains(txtSearchbar.Text.ToLower())).ToList();
foreach (var item in TempVar)
{
ListBoxOne.Items.Add(TempVar);
}
Tell me if you need more information. Thanks for all the help!!
EDIT1:
Dont know if this is the right way to answer, but the comment section didnt let me post a long answer.
For starters. Thanks for being so helpful. I tried your code for adding to the list, but got the errorcode: Cannot convert System.Collecion.Generic.List to System.Windows.Forms.ListBox.ObjectCollection. Searched the web for a solution but came up short. Shall I post my entire code? Also tried your search code it works great. But my main problem is still there. When I click on the search results the name in the listbox shows the contact information of the first contact in the entire contactlist. Its as if the index of the contacts is still in the listbox but when contacts in the Listbox are sorted out by the search function the first contacts index is given to the contact the search found. Shall I post my entire code to make everything clearer.? Thanks for all the help!
EDIT2: Here is the code. I got a class with person propertys. Name, adress, postnummber, city, telephone annd email that links to the list.
I know some of the comments are in swedish and it is a hassle. Ask me if there is anything you donte understand.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Person> People = new List<Person>();//Skapar en lista med alla variabler i Person
private void Form1_Load(object sender, EventArgs e)//Reads file on start up.
{
//string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (Directory.Exists("C:\\visualFolder\\Adressbok"))
{
Directory.CreateDirectory("C:\\visualFolder\\Adressbok");
}
if (!File.Exists("C:\\visualFolder\\Adressbok\\settings.xml"))
{
XmlTextWriter XW = new XmlTextWriter("C:\\visualFolder\\Adressbok\\settings.xml", Encoding.UTF8);
XW.WriteStartElement("People");
XW.WriteEndElement();
XW.Close();
}
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:\\visualFolder\\Adressbok\\settings.xml");
foreach (XmlNode XNode in xDoc.SelectNodes("People/Person"))
{
Person p = new Person();
p.Namn = XNode.SelectSingleNode("Namn").InnerText;
p.GatuAdress = XNode.SelectSingleNode("Adress").InnerText;
p.PostNummer = XNode.SelectSingleNode("Postnummer").InnerText;
p.PostOrt = XNode.SelectSingleNode("Postort").InnerText;
p.Telefon = XNode.SelectSingleNode("Telefon").InnerText;
p.Email = XNode.SelectSingleNode("Email").InnerText;
People.Add(p);
ListBoxOne.Items.Add(p.Namn);
}
}//----
private void cmdRegistrera_Click(object sender, EventArgs e)//Adds contact
{
Person LäggTillPerson = new Person();
LäggTillPerson.Namn = txtNamn.Text;
LäggTillPerson.GatuAdress = txtAdressText.Text;
LäggTillPerson.PostNummer = txtPostNummer.Text;
LäggTillPerson.PostOrt = txtPostOrt.Text;
LäggTillPerson.Telefon = txtTelefonnummer.Text;
LäggTillPerson.Email = txtEpost.Text;
People.Add(LäggTillPerson);
ListBoxOne.Items.Add(LäggTillPerson.Namn);
txtNamn.Clear();
txtAdressText.Clear();
txtPostNummer.Clear();
txtPostOrt.Clear();
txtTelefonnummer.Clear();
txtEpost.Clear();
}
private void cmdTaBort_Click(object sender, EventArgs e)//Deletes contact.
{
if (ListBoxOne.SelectedItem != null)
{
People.RemoveAt(ListBoxOne.SelectedIndex);
ListBoxOne.Items.Remove(ListBoxOne.SelectedItems[0]);
}
txtNamn.Clear();
txtAdressText.Clear();
txtPostNummer.Clear();
txtPostOrt.Clear();
txtTelefonnummer.Clear();
txtEpost.Clear();
}
private void ListboxOne_SelectedIndexChanged(object sender, EventArgs e)//
{
if (ListBoxOne.SelectedItem != null)
{
txtNamn.Text = People[ListBoxOne.SelectedIndex].Namn;
txtAdressText.Text = People[ListBoxOne.SelectedIndex].GatuAdress;
txtPostNummer.Text = People[ListBoxOne.SelectedIndex].PostNummer;
txtPostOrt.Text = People[ListBoxOne.SelectedIndex].PostOrt;
txtTelefonnummer.Text = People[ListBoxOne.SelectedIndex].Telefon;
txtEpost.Text = People[ListBoxOne.SelectedIndex].Email;
}
}
private void cmdSpara_Click(object sender, EventArgs e)//Saves changes.
{
if (ListBoxOne.SelectedItem != null)
{
People[ListBoxOne.SelectedIndex].Namn = txtNamn.Text;
People[ListBoxOne.SelectedIndex].GatuAdress = txtAdressText.Text;
People[ListBoxOne.SelectedIndex].PostNummer = txtPostNummer.Text;
People[ListBoxOne.SelectedIndex].PostOrt = txtPostOrt.Text;
People[ListBoxOne.SelectedIndex].Telefon = txtTelefonnummer.Text;
People[ListBoxOne.SelectedIndex].Email = txtEpost.Text;
ListBoxOne.Items.Clear();
foreach (var item in People)
{
ListBoxOne.Items.Add(item.Namn);
}
}
MessageBox.Show("Ändringarna är sparade");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)//Saves to file on when closin the application.
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:\\visualFolder\\Adressbok\\settings.xml");
XmlNode xNode = xDoc.SelectSingleNode("People");
xNode.RemoveAll();
foreach (Person p in People)
{
XmlNode xTop = xDoc.CreateElement("Person");
XmlNode Xnamn = xDoc.CreateElement("Namn");
XmlNode Xadress = xDoc.CreateElement("Adress");
XmlNode XPostnummer = xDoc.CreateElement("Postnummer");
XmlNode XpostOrt= xDoc.CreateElement("Postort");
XmlNode Xtelefon = xDoc.CreateElement("Telefon");
XmlNode XeMAil = xDoc.CreateElement("Email");
Xnamn.InnerText = p.Namn;
Xadress.InnerText = p.GatuAdress;
XPostnummer.InnerText = p.PostNummer;
XpostOrt.InnerText = p.PostOrt;
Xtelefon.InnerText = p.Telefon;
XeMAil.InnerText = p.Email;
xTop.AppendChild(Xnamn);
xTop.AppendChild(Xadress);
xTop.AppendChild(XPostnummer);
xTop.AppendChild(XpostOrt);
xTop.AppendChild(Xtelefon);
xTop.AppendChild(XeMAil);
xDoc.DocumentElement.AppendChild(xTop);
}
xDoc.Save("C:\\visualFolder\\Adressbok\\settings.xml");
}
private void cmdSök_Click(object sender, EventArgs e)//Search function. This is where the problem is.
{
if (txtSearchbar.Text != "")
{
var term = txtSearchbar.Text;
var results = People.Where(a => ContainsCI(a.Namn, term)
|| ContainsCI(a.PostOrt, term));
foreach (var item in results)
{
ListBoxOne.Items.Add(item);
}
ListBoxOne.Items.Clear();
foreach (var item in results)
{
ListBoxOne.Items.Add(item.Namn);
}
txtSearchbar.Clear();
}
else
{
ListBoxOne.Items.Clear();
foreach (var item in People)
{
ListBoxOne.Items.Add(item.Namn);
}
}
}
private void cmdClearSearch_Click(object sender, EventArgs e)//Clears the searchebar and ListBox and loads the contacts again.
{
ListBoxOne.Items.Clear();
txtSearchbar.Clear();
foreach (var item in People)
{
ListBoxOne.Items.Add(item.Namn);
}
txtNamn.Clear();
txtAdressText.Clear();
txtPostNummer.Clear();
txtPostOrt.Clear();
txtTelefonnummer.Clear();
txtEpost.Clear();
}
public bool ContainsCI(string input, string term)//Search function. courtesy of Panagiotis Kanavos
{
if (String.IsNullOrWhiteSpace(input))
{
return false;
}
//Returns true even if `terms` is empty, just like String.Contains
return input.IndexOf(term, StringComparison.CurrentCultureIgnoreCase) != -1;
}
}
}
Your code has a typo. Instead of adding individual items you keep adding the list itself to the listbox. You should add the individual items:
foreach (var item in TempVar)
{
ListBoxOne.Items.Add(item);
}
A better option though would be to use AddRange to add the entire list at once:
ListBoxOne.Items.AddRange(TempVar);
You can improve the rest of the code as well. Instead of Contains which is case sensitive, you can use IndexOf with a case-insensitive StringComparison parameter. To make the code a bit cleaner, I created a separate ContainsCI method:
public bool ContainsCI(string input, string term)
{
if (String.IsNullOrWhitespace(input))
{
return false;
}
//Returns true even if `terms` is empty, just like String.Contains
return input.IndexOf(term,StringComparison.CurrentCultureIgnoreCase)!= -1);
}
...
var term=txtSearchbar.Text;
var results= People.Where(a => ContainsCI(a.Namn, term)
|| ContainsCI(a.PostOrt,term));
ListBoxOne.Items.AddRange(results);
By using IndexOf instead of Contains and ToLower() the code avoids generating temporary strings which end up wasting memory for no gain.
Note that both String.Contains and ContainsCI return true if the term is empty. This makes it easy to return all items if the search box is empty.
I have asked this question yesterday and i didn't get good response. i am working on a resx file. I have read the file and load it on data-gridview. now i wanted to be able to edit from the file and save.I have tried many ways but i didn't come with the solution. yesterday i tried this code below. I don't know how i can edit. please help me.
private void btnSave_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow _row in Gridview_Output.Rows)
{
DataRow dt1 = oDataTable.NewRow();
for (int i = 0; i < Gridview_Output.ColumnCount; i++)
{
Gridview_Input.SelectedRows[0].Cells[1].Value = oDataSet.Tables["data"].Rows[0][1].ToString();
Gridview_Input.SelectedRows[0].Cells[2].Value = oDataSet.Tables["data"].Rows[0][2].ToString();
Gridview_Input.SelectedRows[0].Cells[3].Value = oDataSet.Tables["data"].Rows[0][3].ToString();
Gridview_Input.SelectedRows[0].Cells[4].Value = oDataSet.Tables["data"].Rows[0][4].ToString();
oDataTable.Rows.Add(dt1);
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(PathSelection);
}
This will help you almost the way you want it.
Code snippet from Modifying .resx file in c#
public static void UpdateResourceFile(Hashtable data, String path)
{
Hashtable resourceEntries = new Hashtable();
//Get existing resources
ResXResourceReader reader = new ResXResourceReader(path);
if (reader != null)
{
IDictionaryEnumerator id = reader.GetEnumerator();
foreach (DictionaryEntry d in reader)
{
if (d.Value == null)
resourceEntries.Add(d.Key.ToString(), "");
else
resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
}
reader.Close();
}
//Modify resources here...
foreach (String key in data.Keys)
{
if (!resourceEntries.ContainsKey(key))
{
String value = data[key].ToString();
if (value == null) value = "";
resourceEntries.Add(key, value);
}
}
//Write the combined resource file
ResXResourceWriter resourceWriter = new ResXResourceWriter(path);
foreach (String key in resourceEntries.Keys)
{
resourceWriter.AddResource(key, resourceEntries[key]);
}
resourceWriter.Generate();
resourceWriter.Close();
}