How can i edit a cell from the datgridview? - c#

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();
}

Related

elastic search field update from csv file in c#

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.

ListView Images misplacing and disappears sometimes in winform c#

I am working on winforms, where I have 2 codes, working for the same thing, and they are same just the query difference but one is working completely fine and other one has issues as it misplace the images.
the problem is everytime I run code, images are at wrong place.
the correct functionality code:
int c2 = -1;
List<string> searchpath =new List<string>();
List<string> searchtitle = new List<string>();
listView2.Clear();
homerecipe.Clear();
searchtitle.Clear();
searchpath.Clear();
imageList3.Images.Clear();
var text = textBox1.Text;
char[] separator = { ' ' };
string[] words = null;
words = text.Split(separator);
foreach (string word in words)
{
try
{
cmd = new SqlCommand($"select Title, Thumbnail,RecipeName from RecipeInfo where RecipeName like '%{word}%'", con);
con.Open();
SqlDataReader read = cmd.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
// if (homerecipe.Any(item => item == read[2].ToString())) continue;
searchtitle.Add(read[0].ToString());
searchpath.Add($#"{read[1].ToString()}");
homerecipe.Add(read[2].ToString());
}
read.Close();
//con.Close();
foreach (string ipath in searchpath)
{
ListViewItem img = listView2.FindItemWithText(ipath);
if (img == null)
{
imageList3.Images.Add(Image.FromFile(ipath));
}
}
listView2.LargeImageList = imageList3;
foreach (string hometitle in searchtitle)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
c2++;
listView2.Items.Add(hometitle, c2);
}
}
}
con.Close();
}
catch (SqlException)
{
MessageBox.Show("masla");
con.Close();
//continue;
}
The problematic code:
int ccc = -1;
hometitles.Clear();
homepaths.Clear();
homerecipe.Clear();
imageList2.Images.Clear();
try
{
cmd = new SqlCommand("select Title, Thumbnail,RecipeName from RecipeInfo order by newid()", con); //generating random from sql
con.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
hometitles.Add(reader1[0].ToString());
homepaths.Add($#"{reader1[1].ToString()}");
homerecipe.Add(reader1[2].ToString());
}
}
reader1.Close();
//con.Close();
foreach (string imagepath in homepaths)
{
ListViewItem img = listView2.FindItemWithText(imagepath);
if (img == null)
{
imageList2.Images.Add(Image.FromFile(imagepath));
}
}
listView2.LargeImageList = imageList2;
foreach (string hometitle in hometitles)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
ccc++;
listView2.Items.Add(hometitle,ccc);
}
}
con.Close();
}
catch(SqlException)
{
MessageBox.Show("error");
}
I have tried using the homerecipe elements as image key as they are primary key but I don't know how to give a condition in foreach that if one name entered then the same name don't come twice.
for this, i was trying this
foreach (string imagepath in homepaths)
{
foreach(string name in homerecipe) //name a primary key
{
ListViewItem img = listView2.FindItemWithText(imagepath);
if (img == null)
{
MessageBox.Show(name);
imageList2.Images.Add(name,Image.FromFile(imagepath));
}
}
}
listView2.LargeImageList = imageList2;
foreach (string hometitle in hometitles)
{
foreach (string name in homerecipe)
{
ListViewItem list = listView2.FindItemWithText(hometitle);
if (list == null)
{
ccc++;
listView2.Items.Add(hometitle, name);
}
}
}
I am trying this for the last 3 days, please help me correct it. please I am in the deadline for my project but this issue is not resolving. I am new to programming please resolve this issue.
Sometimes, it happens that only images shuffle, sometimes both text and image but not correct positon
After reading the data from the database, in
while (reader.Read()){}
fills the ListView directly, which can make the code more concise and clear.
I wrote a similar example, you can refer to it.
Pictures fill ListView

How to use AutoSuggest from a DataBase in a textbox?

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;
}

asp.net c# txt file to dropdownlist:

I need to populate a drop down list with a txt file. I tried this but it isn't working.
protected void DropDownListCOUNTRY_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> country = new List<string>();
country = File.ReadAllLines("../App_Data/txt/CountryList.txt").Select(x => x.Split('_')[0]).ToList();
foreach (string countrysingle in country)
{
DropDownListCOUNTRY.Items.Add(new ListItem(countrysingle, countrysingle));
}
}
This is the VB code that works in C#
if (this.IsPostBack == false)
{
string path = MapPath("~/App_Data/txt/CountryList.txt");
FileStream fp = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fp);
string data;
while ((data = reader.ReadLine()) != null)
{
string[] v = data.Split(',');
foreach (string entry in v)
{
DropDownListCOUNTRY.Items.Add(entry);
}
}
reader.Close();
fp.Close();
}
The VB code in my initial question works.
I think you have to give variable declaration also in foreach loop like below
foreach (string countrysingle in country) {
DropDownListCOUNTRY.Items.Add(countrysingle);
}

Loading User Control Dynamically

I have my code as below
string[] keys = { "myCustomUserControl.ascx", "myCustomUserControl.ascx.cs", "myCustomUserControl.ascx.designer.cs" };
string customUserControlName = CommonDataCalls.GetCustomUserControlName(keys);
UserControl objUserControl = (UserControl)this.LoadControl("~/UserControls/" + userControlName);
userControlPlaceHolder.Controls.Add(objUserControl);
The definition of GetCustomUserControlName is as below
public string GetCustomUserControlName(string[] keys)
{
try
{
string userConrolsPhysicalPtah = System.Web.HttpContext.Current.Server.MapPath("~/UserControls/");
DataTable objDataTable = new DataTable();
foreach (string key in keys)
{
objRequestVO.addObject("ACA_KEY", key);
CResponseVO objResponseVO = (CResponseVO)objGateway.ExecuteBusinessService(CConstant.ADMIN, CConstant.ASSEMBLY_INFO, CConstant.SELECT, objRequestVO);
DataSet objDataSet = (DataSet)objResponseVO.getObject("RES_DS");
cUserTrce objGeneral = new cUserTrce();
if (!objGeneral.IsNullOrEmptyDataset(objDataSet))
{
if (objDataTable.Rows.Count == 0)
{
objDataTable = objDataSet.Tables[0].Clone();
}
objDataTable.Rows.Add(objDataSet.Tables[0].Rows[0].ItemArray);
}
}
if (objDataTable != null && objDataTable.Rows.Count == 3)
{
string containerName = "usercontrols";
foreach (DataRow dr in objDataTable.Rows)
{
string userControlFileBlobUrl = dr["ACA_ASSEMBLY_PATH"].ToString();
string userControlFileName = dr["ACA_CLASS_NAME"].ToString();
Storage.Blob blobHandler = new Storage.Blob();
Stream blobstream = blobHandler.GetBlob(userControlFileBlobUrl, containerName);
if (!(File.Exists(userConrolsPhysicalPtah + userControlFileName)))
{
MemoryStream ms = (MemoryStream)blobstream;
FileStream outStream = File.OpenWrite(userConrolsPhysicalPtah + userControlFileName);
ms.WriteTo(outStream);
outStream.Flush();
outStream.Close();
}
}
string customUserControlName = (from DataRow row in objDataTable.Rows
where row["ACA_KEY"].ToString() == keys[0]
select row["ACA_CLASS_NAME"].ToString()).First();
return customUserControlName;
}
else
{
return null;
}
}
catch
{
return null;
}
}
The mithod basically copies the user controls to the virtual path at run time .
In aspx.cs page I try to load it dynamically .
But I can see the file is getting copied to the virtual path but this. Load control gives me exception saying Could not load type 'myCustomUserControl'.
I am using azure web role
What is wrong here ?
I solved the bug . I am just putting here for anyone to refer .
It's a one word change -
http://blog.kjeldby.dk/2008/11/dynamic-compilation-in-a-web-application/
Change
CodeBehind="myCustomUserControl.ascx.cs"
to
CodeFile="myCustomUserControl.ascx.cs"
Thanks to #Roopesh & #Kristoffer Brinch Kjeldby
and it will start working.

Categories