Had a look around and can't figure out how to do this.
I'm trying to query a datatable. I search the first column for the string value, and I need to return the integer that corresponds to it in the second column.
When I have that integer, I need to add 1 to the integer value and edit the row with the updated information.
public static string hashtag_counter(string message)
{
int hashcounter = 0;
DataTable hashtags = new DataTable();
DataRow row = new DataRow();
hashtags.Columns.Add("Hashtag", typeof(string));
hashtags.Columns.Add("Count", typeof(int));
string[] words = message.Split(' ');
foreach (string word in words)
{
if (word.StartsWith("#"))
{
if (hashtags.Columns.Contains(word))
{
DataRow[] selection = hashtags.Select("Hashtag == " + word);
}
}
else
{
row = hashtags.NewRow();
row["Hashtag"] = word;
row["Count"] = "1";
hashtags.Rows.Add(row);
}
I can't seem to find this anywhere, so any help would be appreciated
If I follow the requirements in your question, then your code should be like this.
.....
string[] words = message.Split(' ');
// Execute the loop ONLY for the required words (the ones that starts with #)
foreach (string word in words.Where(x => x.StartsWith("#")))
{
// Search if the table contains a row with the current word in the Hashtag column
DataRow[] selection = hashtags.Select("Hashtag = '" + word + "'");
if(selection.Length > 0)
{
// We have a row with that term. Increment the counter
// Notice that selection is an array of DataRows (albeit with just one element)
// so we need to select the first row [0], second column [1] for the value to update
int count = Convert.ToInt32(selection[0][1]) + 1;
selection[0][1] = count;
}
else
{
row = hashtags.NewRow();
row["Hashtag"] = word;
row["Count"] = "1";
hashtags.Rows.Add(row);
}
}
Notice that if you want to Select on a string field then your need to use quotes around the search term and you don't need to use == like in C#
Related
I am trying to convert the content of a Clipboard to Datatable.
I was trying to use the following code from the URL: http://www.seesharpdot.net/?p=221
private void PasteFromExcel()
{
DataTable tbl = new DataTable();
tbl.TableName = "ImportedTable";
List<string> data = new List<string>(ClipboardData.Split('\n'));
bool firstRow = true;
if (data.Count > 0 && string.IsNullOrWhiteSpace(data[data.Count - 1]))
{
data.RemoveAt(data.Count - 1);
}
foreach (string iterationRow in data)
{
string row = iterationRow;
if (row.EndsWith("\r"))
{
row = row.Substring(0, row.Length - "\r".Length);
}
string[] rowData = row.Split(new char[] { '\r', '\x09' });
DataRow newRow = tbl.NewRow();
if (firstRow)
{
int colNumber = 0;
foreach (string value in rowData)
{
if (string.IsNullOrWhiteSpace(value))
{
tbl.Columns.Add(string.Format("[BLANK{0}]", colNumber));
}
else if (!tbl.Columns.Contains(value))
{
tbl.Columns.Add(value);
}
else
{
tbl.Columns.Add(string.Format("Column {0}", colNumber));
}
colNumber++;
}
firstRow = false;
}
else
{
for (int i = 0; i < rowData.Length; i++)
{
if (i >= tbl.Columns.Count) break;
newRow[i] = rowData[i];
}
tbl.Rows.Add(newRow);
}
}
this.WorkingTableElement.WorkingTable = tbl;
tableImportGrid.DataSource = null;
tableImportGrid.RefreshDataSource();
tableImportGrid.DataSource = tbl;
tableImportGrid.RefreshDataSource();
tableImportGrid.Refresh();
}
But the following part of the code:
List<string> data = new List<string>(ClipboardData.Split('\n'));
is causing me some trouble. I understand that the ClipboardData should already refer to Clipboard content, but I tried to do that with DataObject, but this did not work.
Maybe someone has a good idea how to implement this or some guidelines how to go forward. I have not been exposed to C# much and mostly done my programming in Python.
Split is a function available to the String class, so I'd assume ClipboardData should be a string.
This can be retrieved by calling: System.Windows.Forms.Clipboard.GetText(), rather than Clipboard.GetDataObject(), which I assume you are calling at the moment.
On calling the GetText() method, the selected cells are converted to their textual representation, with each cell separated by a space (or tab?), and each line separated by a newline character ('\n'). Something like this:
1 2 3 4 5 6
a b c d e f
TL;DR; you should call Clipboard.GetText(), rather than Clipboard.GetDataObject().
How do I get the data of a specific row stored in a list box by clicking on the particular row ? So if i click on the row i can then access that particular row by index then store it to be used later on
int myMaxResultValue = (int)nud_MaxResults.Value;
int myMaxSuggestValue = (int)nud_MaxSuggestions.Value;
findResults = objBvSoapClient( txt_Search.Text, txt_LastId.Text, cb_SearchFor.Text, text_Country.Text, text_LanguagePreference.Text, myMaxResultValue, myMaxSuggestValue);
if (txt_Search.Text.Length <= 2)// if less than two letters are entered nothing is displayed on the list.
{
ls_Output.Items.Clear();// Clear LstBox
ls_Output.Items.Add(String.Format(allDetails, "ID", "Text", "Highlight", "Cursor", "Description", "Next"));
MessageBox.Show("Please enter more than 2 Chars!!");
}
else if (txt_Search.Text.Length >= 3)// if greater than or equal to 3 letters in the search box continue search.
{
// Get Results and store in given array.
foreach (var items in findResults)
{
//Loop through our collection of found results and change resulting value.
ls_Output.Items.Add(String.Format(allDetails, items.Id, items.Text.ToString(), items.Highlight, items.Cursor, items.Description, items.Next));
}
}
Then to retrieve the whole string i have placed this function within the indexChanged event,:
if (ls_Output.SelectedIndex != -1)
{
int itemAtPostion = ls_Output.SelectedIndex;
string nextStep = "Retrieve";
if (ls_Output.Items[itemAtPostion].ToString().Contains(nextStep))
{
string selItem = ls_Output.SelectedItem.ToString();
MessageBox.Show("You have selected the following address: " + selItem);
lst_Retreive.Text = ls_Output.SelectedItem.ToString();
}
}
You can either get the index of the item or the item itself.
To get the item you can use
string item = listBox.SelectedItem.ToString();
To get the index of the item you can use
int idx = listBox.SelectedIndex;
If your listbox supports multiselect you can use
var items = listBox.SelectedItems();
and
var idx = listBox.SelectedIndices;
I was looking at this in a completly different way, and i should have been thinking about DataTables. I wanted to only be clicking on individual cells and hence the reason I was getting the whole string back rather than individual feilds. Heres how i Solved it
DataTable ss = new DataTable();
ss.Columns.Add("ID");
ss.Columns.Add("Text");
ss.Columns.Add("Highlight");
ss.Columns.Add("Cursor");
ss.Columns.Add("Description");
ss.Columns.Add("Next");
DataRow row = ss.NewRow();
row["ID"] = findResults[0].Id;
row["Text"] = findResults[0].Text;
row["Highlight"] = findResults[0].Highlight;
row["Cursor"] = findResults[0].Cursor;
row["Description"] = findResults[0].Description;
row["Next"] = findResults[0].Next;
ss.Rows.Add(row);
foreach (DataRow Drow in ss.Rows)
{
int num = dataGridView1.Rows.Add();
dataGridView1.Rows[num].Cells[0].Value = Drow["id"].ToString();
dataGridView1.Rows[num].Cells[1].Value = Drow["Text"].ToString();
dataGridView1.Rows[num].Cells[2].Value = Drow["Highlight"].ToString();
dataGridView1.Rows[num].Cells[3].Value = Drow["Cursor"].ToString();
dataGridView1.Rows[num].Cells[4].Value = Drow["Description"].ToString();
dataGridView1.Rows[num].Cells[5].Value = Drow["Next"].ToString();
}
if (txt_Search.Text.Length <= 2)// if less than two letters are entered nothing is displayed on the list.
{
MessageBox.Show("Please enter more than 2 Chars!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
findResults.Clear();
In my firstform, the gridview shows this:
and then i want to parsing to secondform iam using this code
string asscode = gridView1.GetFocusedRowCellValue("AsstCode").ToString();
Assistant assist = new Assistant(asscode);
assist.show();
When parsing, the string is one variable, so i need to split them. I'm using this split to break them
string ass_code;
public Assistant(string z) //this is form 2
{
InitializeComponent();
ass_code = z;
}
in second form i already set a gridview.datasource from another query and so i need to add custom column to the gridview, iam using this code
private void button1_Click(object sender, EventArgs e)
{
string[] names = ass_code.Split(';');
gridView1.BeginUpdate();
DataColumn col = dt.Columns.Add("X", typeof(Boolean));
GridColumn column = gridView1.Columns.AddVisible(col.ColumnName);
column.Caption = col.Caption;
column.Name = col.ColumnName;
gridView1.EndUpdate();
}
for the secondform interface, the gridview display this
what i want to ask is
how do i make the column x got checked base on the asscode so 0110300 and 0110164 and the other value not checked. as you can see on column x it got gray colour which the value is not 1 or 0
when i try to
//string[] names = ass_code.Split(';');
//foreach (string xy in names)
//{
// MessageBox.Show(xy);
//}
it shows that the first was 0110159 but the second string 0110164 got space string on the first character. << because this use for list 1
UPDATE:
well iam using this code but its only check on 0110300 because it set 0110159 back to false
foreach (string x in names)
{
string[] names = ass_code.Split(';');
for (int i = 0; i < gridView1.RowCount; i++)
{
string xg = x.Trim();
string g = gridView1.GetDataRow(i)["code"].ToString().Trim();
if (g == xg)
{
gridView1.SetRowCellValue(i, "Dada", true);
}
else
{
gridView1.SetRowCellValue(i, "Dada", false);
}
}
}
UPDATE2
If leading / trailing spaces is cause of issue then you can do it in two ways:
first way:
string[] names = ass_code.Split(';');
// remove leading / trailing spaces
for (int i = names.Length-1; i >= 0; i-- )
names[i] = names[i].Trim();
second way:
string[] names = ass_code.Split(new char[] { ';', ' '}, StringSplitOptions.RemoveEmptyEntries);
You make to much handy stuff. The Devexpress Grid is really much simpler to use:
var data = //GETYOURDATA
gridControl.DataSource = data;
This populates your data to the grid. You even don't need to create any columns etc. If you want a value now, you shouldn't use GetRowCellValue(); Try to use your DataSource instead.
var actualRow = gridView.GetFocusedRow() as DataRowView;
MessageBox(actualRow["code"]); //Will print your code from code column
What you need to understand is that your DataSource is the source of trues and the GridView just show this data. This becomes more comfortable if you store your data in List<T>.
EXAMPLE:
public class Employee()
{
public int Code{get;set}
public string Name{get;set;}
public bool X {get{return Code == 0110300}}
public static List<Employee> ReadAll(){//Get your data};
}
public class MyForm() : XtraForm
{
var data = Employee.ReadAll();
gridControl.DataSource = data;
//Access Employee code
Employee emp = gridView.GetFocusedRow() as Employee;
MessageBox.Show(emp.Code.ToString());
}
UPDATE
Use the second approach from #Rupesh to remove your spaces. And uses Equals for string comparison. Further set your GridColumn 'X' to column.UnboundType = DevExpress.Data.UnboundColumnType.Bool; to make sure DevExpress don't override your data.
UPDATE-2
var names = ass_code.Split(';').Select(p => p.Trim()).ToList();
for (int i = 0; i < gridView1.RowCount; i++)
{
string g = gridView1.GetDataRow(i)["code"].ToString().Trim();
if (names.Contains(g))
gridView1.SetRowCellValue(i, "Dada", true);
else
gridView1.SetRowCellValue(i, "Dada", false);
}
I know the title is not appropriate,Im unable to put it in a single statement.,When the university results are published,the results of each student have to be retrieved individually,my task is to retrieve,a particular number of records,based on the textbox values in my aspx page(eg:1-10) and display them in an Excel sheet in a particular format(if you notice the university website,when a roll number is typed,for each student the results are displayed in a table format,with subject codes as first column,grades 2nd column,status as 3rd column,my task is to display them in an Excel sheet like:first row alone will be subject codes,remaining rows will display the grades of the particular number of students).I have created a webpage using asp.net-c#,im using xpath to retrieve the values from university website.I partially succeeded,still my output is not exact.I assumed that if the subject codes of the first record are alone displayed in the first row of the Excel sheet,then its easy to display the grades(2nd column)values of all the remaining numbers.
The code works fine,when the sequential numbers do not have arrear results,when there is an arrear result(which will not be orderedly displayed in the website,then the values are overwritten in the excel sheet,and finally extra subjects(arrear subject codes)are not displayed with their code in the 1st row(that is cause,the 1st roll number might have not had an arrear) now im unable to solve this issue,im having no idea how to retrieve the column values and correctly display,pls help.
//my code:
int rowno=2;
for(j=from;j
//retrieve the first column values of 1st roll number
var query = from table in doc.DocumentNode.SelectNodes("//table[2]").Cast<HtmlNode>()
from row in table.SelectNodes("tr[position()>2]").Cast<HtmlNode>()
from cell in row.SelectNodes("td[1]").Cast<HtmlNode>()
select new { CellText = cell.InnerText };
int cc = 1;
foreach (var cell in query)
{
int rwn = 1;
if (cc == 1)
{
myExcelWorksheet.get_Range("C" + rwn, misValue).Formula = cell.CellText;
}
if (cc == 2)
{
myExcelWorksheet.get_Range("D" + rwn, misValue).Formula = cell.CellText;
}
if (cc == 2)
{
myExcelWorksheet.get_Range("D" + rwn, misValue).Formula = cell.CellText;
}
if (cc == 3)
{
myExcelWorksheet.get_Range("E" + rwn, misValue).Formula = cell.CellText;
}
}
//retrieve the second column values of all roll number
var query1 = from table in doc.DocumentNode.SelectNodes("//table[2]").Cast<HtmlNode>()
from row in table.SelectNodes("tr[position()>2]").Cast<HtmlNode>()
from cell in row.SelectNodes("td[2]").Cast<HtmlNode>()
select new { CellText = cell.InnerText };
string ans = "";
int cc = 1;
foreach (var cell in query1)
{
if (cc == 1)
{
myExcelWorksheet.get_Range("C" + rowno, misValue).Formula = cell.CellText;
}
if (cc == 2)
{
myExcelWorksheet.get_Range("D" + rowno, misValue).Formula = cell.CellText;
}
if (cc == 3)
{
myExcelWorksheet.get_Range("E" + rowno, misValue).Formula = cell.CellText;
}}
I have a ListView. My main goal is to be able, to copy the ListViewItems to the Clipboard and then to Excel. But I have troubles to read the ListView Cells.
To get the Columns I use:
var columnNames = new StringBuilder();
foreach (GridViewColumn column in ((GridView)(listViewSolution.View)).Columns)
{
columnNames.Append(column.Header + "\t");
}
Now I want to add the rows, but I'm only able to access the first Cell in the first column, not the second or third..:
var stringBuilder = new StringBuilder();
for (int i = 0; i < listViewSolution.Items.Count; i++)
{
stringBuilder.Append("\n");
//foreach (GridViewColumn column in ((GridView)(listViewSolution.View)).Columns)
//{
//if (column.Header != null)
//{
ListViewItem myListBoxItem =
(ListViewItem)(listViewSolution.ItemContainerGenerator.ContainerFromIndex(0)); //= Index 0 -> First Row, First Cell; Index 1 = Second Row, First Cell; But do we get: Second Column, First Row????
stringBuilder.Append(myListBoxItem.Content.ToString() + "\t");
//}
//}
}
System.Windows.Clipboard.SetData(DataFormats.Text, columnNames.ToString() + stringBuilder.ToString());
Help would be much appreciated..
You're not changing the index in the .ContainerFromIndex call each iteration. Use your loop variable there and see what you get.