How to add Ms-Access database column in any String [] in C# - c#

I am a newbie to C#.
I want to add my one of database's column in string[] but fail to do so. I have created string[] with name "Items" and also create a control with name autocompletemenu1. Now when I type autocompetemenu1.Items = Database Column then the contents of database column should be filled in ITEM string[]. I have tried but it is not working so I just mention some name in it and it is working but it is not taking database column. Don't know why! Please help
Thank you in advance.
This is the method ITEM I am using to take collections. Way to write is
autocompleteMenu1.Items = Database column
My code:
[DefaultValue(null)]
public string[] Items
{
get
{
if (sourceItems == null)
return null;
var list = new List<string>();
foreach (AutocompleteItem item in sourceItems)
list.Add(item.ToString());
return list.ToArray();
}
set { SetAutocompleteItems(value);
}
Here is the assignment of String [] to Item method but I want to add database column instead of string [] ... how can I do this...?
this.autocompleteMenu1.Items = new string []
{
"Jamal",
"Javed",
"Jameel",
"James",
"Jamshed",
"abc",
"abcd",
"Ahmed",
};

Related

List of strings stored as values in dictionary C#

I have a testing framework that needs to be updated to include testing in Spanish. I have a CSV file that contains the field label, english text, and Spanish text. I've decided to use a dictionary to store the field label as the key and the values would be a list of strings for Spanish and English text.
private List<string> ReadTranslationCsv()
{
var pathToCSV = #"C:\Location";
Dictionary<string, List<string>> translations = new Dictionary<string, List<string>>();
string label, englishText, spanishText;
using (TextReader fileReader = File.OpenText(pathToCSV))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
while (csv.Read())
{
for (int i = 0; csv.TryGetField<string>(i, out label);)
{
List<string> Spanglish = new List<string>();
csv.TryGetField<string>(i + 1, out englishText);
Spanglish.Add(englishText);
csv.TryGetField<string>(i + 2, out spanishText);
Spanglish.Add(spanishText);
if (label != "")
{
translations.Add(label, Spanglish);
}
i = i + 3;
}
}
}
}
I want to be able to search within the list of values to see if anything matches some string of text. I'm not sure how to search the lists that are within the dictionary, none of the default methods or properties are working.
I'm using the below code but this will return me a bool, which is not what I need, I need the list value that matches the elementWithText
public void GivenElementMatches(string elementWithText)
{
if (Config.Language == "Spanish")
{
var list = new List<string> { elementWithText };//must create list in order to pass text to any translations methods
Hooks.translations.ContainsValue(list); // Even though the labels are the key, I need to search for the english text which is index 1 of the list and all values should be returned
}
//TODO
}
My suggestion would be to use a Dictionary with a class you create, inside that class you can have a compare function.
The advantage of this method is you may add more language equivalents later and only have to change your model.
Please note, this code is not complete and you will have to bug check and alter it to suit.
Dictionary <string, LangEquivalents> model;
public KeyValuePair<string, LangEquivalents> findField(string input)
{
return model.First(x=>x.Value.Comparison(input));
}
You could also make it a comparable object type and just use model.First(x=>x.Value == input));

SharePoint Lookup ListItem not loading value

I am importing a database into SharePoint Lists. I have a list of Plants that are owned by Companies.
Plants have columns for "Plant Name", "Company", "State", "Address", and so on. "Plant Name" and "Address" are both single text lines but "Company" and "State" are lookup types. The "Company" column should look up a name on the "Company" list and link to it. The same for the "State" column linking to the "State" list.
Here is a snippet of my code:
SP.ClientContext context = new SP.ClientContext("http://localhost");
...
newPlantLocation["Company"] = GetItemId(context, "Title", companyName, "Companies");
newPlantLocation["State"] = GetItemId(context, "Title", plantState, "States");
newPlantLocation["Title"] = plantName;
newPlantLocation["Address_x0020_Line_x0020_1"] = plantAddressLine1;
...
newPlantLocation.Update();
and here is the function that returns the ID of the item, it's not the most efficient but easy to follow:
private static int GetItemId(SP.ClientContext context, string columnName, string displayName, string listName)
{
SP.List list = context.Web.Lists.GetByTitle(listName);
SP.CamlQuery query = new SP.CamlQuery();
SP.ListItemCollection items = list.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (SP.ListItem listItem in items)
{
if (listItem[columnName].Equals(displayName))
{
return listItem.Id;
}
}
return 0;
}
The problem that I'm coming across is that when the importer runs, the plants populate the "Plants" list but the "Company" field is left blank. I'm confused because the "State" field is done pretty much the same way and it somehow ends up populated. I've debugged it and the GetItemId function returns the correct integer of the company, it just isn't showing up or saving to the item.
If I do the following, it all of a sudden starts working:
newPlantLocation["Company"] = 4;
I got it solved now.
It seems that this line, context.ExecuteQuery();, was causing trouble and I was prematurely executing the query before the ListItem was updated.
So I changed my GetItemId function to update the ListItem before doing anything.
private static int GetItemId(SP.ClientContext context, string columnName, string displayName, string listName, SP.ListItem thisItem)
{
thisItem.Update();
//this rest of the code is the same
...
}

Moving the column of RenderTable

I have a renderTable and I am adding rows and columns to the table as follows-
RenderTable renderTable = new RenderTable();
DataTable dt = GetData();
foreach (DataRow row in dt.Rows)
{
var header = renderTable.Rows[renderTable.Rows.Count];
header[0].Text = "Column 1";
header[1].Text = "Column 2";
header[2].Text = "Column 3";
header[1].Text = "Column 4";
var data = renderTable.Rows[renderTable.Rows.Count];
data [0].Text = row["col1"].ToString(); // 10
data [1].Text = row["col2"].ToString(); // 11
data [2].Text = row["col3"].ToString(); // 12
data [3].Text = row["col4"].ToString(); // 13
}
This is working fine and table is rendering as folllows-
Column 1 Column2 Column3 Column4
10 11 12 13
My requirement is, now I want to move the column 4 to another place like 2nd place as follows . (this place can differ depending on condition)
Column 1 Column4 Column2 Column3
10 13 11 12
I tried Insert method but it is not working for me as the insert index may change.
Is there any function of render table to move the column to specified index.
Please suggest any alternative if any.
We regret to mention but there isn't any function that can allow the moving of column of RenderTable to a specified index since the Cols of C1PrintDocument is ReadOnly.
I've done this by creating a new class from System.Web.UI.WebControls.GridView. I override CreateColumns which is used to return an array of the column objects in order. I read a cookie from the page (this allows me to change the columns via a cookie on the page) and create a new column array based on the cookie. This cookie is just a string of the column names in the order required with a | separator. I had another column picker page that would set this cookie. If you don't need to change the columns with a cookie this is not needed -- you could read / create this string from a database or configuration file. I believe the code is well commented and clear -- one note, our application has a requirement to include hidden columns, so I add those to the end of the column list before I return the array.
using System.Collections;
using System.Linq;
using System.Web.UI.WebControls;
public class ChangeColumnGridView : System.Web.UI.WebControls.GridView
{
protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
{
// Get the needful from the base class
var baseColList = base.CreateColumns(dataSource, useDataSource);
var inColList = baseColList.OfType<object>();
// Get our column order
string columnOrder;
if (Page.Request.Cookies["colOrder"] != null)
columnOrder = Page.Request.Cookies["colOrder"].Value;
else
return baseColList;
// change it to an array
string[] columnOrderA = columnOrder.Split(new char[] { '|' });
// this is where we will put our results
ArrayList newColumnList = new ArrayList();
// look for each name in the list and add when we find it.
foreach (string name in columnOrderA)
{
var found = inColList.Where((c) => c.ToString() == name).FirstOrDefault();
if (found != null)
newColumnList.Add(found);
}
// look for non-visible items in the list and add them if we don't already have them.
foreach (var a in inColList)
{
if (((System.Web.UI.WebControls.DataControlField)a).Visible == false)
{
var found = newColumnList.Cast<object>().Where((c) => c.ToString() == a.ToString()).FirstOrDefault();
if (found == null)
newColumnList.Add(a);
}
}
return newColumnList;
}
}

loop through database item, sum values and parse unwanted text

I am wondering about for each loop. What I have is several columns for each item and I want to loop trough it and take out values from each column that has the name "inch".
Now to the part where the value is not just numbers but also letters, like "1 inch".
So I have 3 items that has "1 inch","5 inch" and "10 inch".
So I want to take the "inch" (parse I guess) out and add these three together so the sum is 16.
This if for windows phone local database c#
I have a ViewModel and a Model. The columns in the Model looks like this
private string _itemSpring;
[Column]
public string ItemSpring
{
get { return _itemSpring; }
set
{
if (_itemSpring != value)
{
NotifyPropertyChanging("ItemSpring");
_itemSpring = value;
NotifyPropertyChanged("ItemSpring");
}
}
}
Then i view it through my viewmodel with connection string to db,
// LINQ to SQL data context for the local database.
public ToDoDataContext toDoDB;
// Class constructor, create the data context object.
public ToDoViewModel(string toDoDBConnectionString)
{
toDoDB = new ToDoDataContext(toDoDBConnectionString);
}
If your 3 items are like this,
string[] items = { "1 inch", "5 inch", "10 inch" };
int totalCount = 0;
foreach(var item in items)
{
string[] substrings = item.split(' ');
totalCount += int.Parse(substrings[0]);
}
string finalString = totalCount + " inch";
UPDATE:
I dont understand whether you are asking on how to retrieve the data from database or how to process the data that is fetched from DB.
Assuming the second case, check the following answer
Fetch the data from database and convert it into a List or an ObservableCollection
and then you can use the following query on that to get what you want.
foreach(var item in ItemsList)
totalCount += double.Parse(item.ItemSize.Split(' ')[0]);
or otherwise
foreach(var item in ItemsList)
totalCount += double.Parse(item.ItemSize.Replace(" inch", ""));

Filtering list objects from another list

I have the following class in my C# .NET 3.5 win forms app:
class Field {
string objectName;
string objectType;
string fieldName;
string fieldValue;
}
and a List fieldList that is a datasource for a checkedlistbox. This listbox shows all the distinct objectNames from my fieldList collection.
I want to create another checkedlistbox that contains fieldNames, but only shows fieldnames that have an associated checked objectName in the first list box.
So my question is how can I query the DataSource of the original list of objectNames to return the distinct set of fieldNames that are associated with a selected objectName?
That is not very easy to read so I will give an example:
Field1 {
objectName = 'objA'
FieldName = 'FieldA'
}
Field2 {
objectName = 'objA'
FieldName = 'FieldB'
}
Field3 {
objectName = 'objB'
FieldName = 'FieldA'
}
Field4 {
objectName = 'objC'
FieldName = 'FieldC'
}
So suppose in my checkbox I select objectNames objA and objB. Then my returned fields would be 'FieldA' and 'FieldB'.
How can I achieve this using LINQ or filtering my generic list of Fields? Can I utilise the 'select' or 'where' methods that are available to a list?
First, read the object names into an array or list; I'll fake that part. Then it should be something like:
string[] objectNames = { "objA", "objC" };
var hashSet = new HashSet<string>(objectNames);
var qry = (from row in data
where hashSet.Contains(row.objectName)
select row.fieldName).Distinct().ToList();
(edit)
To get the selected names (the bit I faked) you could try (untested):
var selectedNames = namesCheckedListBox.CheckedItems.Cast<Field>()
.Select(field => field.objectName);
var hashSet = new HashSet<string>(selectedNames);
(note no need to use Distinct() in the above, since HashSet<T> does that anyway)
var selectedNames = ... // List of selected names
var selectedFields = (from f in fieldList
where selectedNames.Contains(f.objectName)
select f.FieldName).Distinct().ToList();

Categories

Resources