My application contains ListView with files that i am handling and have 3 columns: file name, length and status.
Inside my for loop i am handling file after file and want in this case to change the status column from wait which is the value at the beginning to in process.
is it possible to change one column ?
lvFiles is my ListView
for (int i = 0; i < lvFiles.Items.Count; i++)
{
//here i am do things with my file
}
Here i am adding files into my ListView:
ListViewItem item = new ListViewItem(new string[] { new FileInfo(filePath).Name, duration, "Waiting" });
Use SubItems property of ListViewItem:
foreach(ListViewItem item in lvFiles.Items)
item.SubItems[2].Text = "Waiting";
You can try something like this if you know the specific Column for example Address would be
colString[2] you can do a single line
string[] colString = new string{ "Starting", "Paused", "Waiting" };
int colIndex = 0;
foreach (ColumnHeader lstViewCol in lvFiles.Columns)
{
lstViewCol.Text = colString[colIndex];
colIndex++;
}
for single column you stated you wanted the 3rd column then you could something like this
lvFiles.Colunns[2] = "waiting";
Related
Is there any way to remove "columns" from an ArrayList?
I got this site up and running before attempting populating my DropDownLists from txt files so I hard-typed each value in. Now I've made an ArrayList from each DropDownList so I can display those lists in DataGridView on the site. The only issue is that "Enabled" and "Selected" show up as columns and I cannot seem to remove the column in the ArrayList, or specify which columns to bring in when creating the ArrayList, or GridView using GridView.Columns.Remove(); because the integers 0 or 1 or 2 don't seem to correspond with anything and the site doesn't run and I can't specify a string as the column title for what to remove.
The DataGrids show up with columns as |Enabled|Selected|Text|Value|
Here's the code for this piece as it stands (You can see what I've tried out and that didn't work that I've commented away):
// Create ListArrays from DropDownLists
ArrayList BuildingList = new ArrayList(Building.Items);
ArrayList DepartmentList = new ArrayList(Department.Items);
//Building.Items.Remove("Enabled");
//Building.Items.Remove("Selected");
// Populate Building GridView
BuildingGrid.DataSource = BuildingList;
BuildingGrid.DataBind();
//BuildingGrid.Columns.Remove;
//BuildingGrid.Columns[0].Visible = false;
// Populate Department GridView
DepartmentGrid.DataSource = DepartmentList;
DepartmentGrid.DataBind();
//DepartmentGrid.Columns[0].Visible = false;
//DepartmentGrid.Columns[1].Visible = false;
I would just go ahead and create a simple 2d array in a txt file with fields for "Value" and "Text" so the DropDownList will pull it in properly, but I can't figure that out either without being terribly inefficient and confusing.
Any help would be appreciated. Thanks.
So, here's the solution I ended up at. I finally figured out how to extract everything from a txt file, and place it into the grid the way I wanted to.
// Populate Department GridView
// get all lines of csv file
string[] BuildingString = File.ReadAllLines(Server.MapPath("Content/BuildingsCSV.csv"));
string[] DepartmentString = File.ReadAllLines(Server.MapPath("Content/DepartmentsCSV.csv"));
// create new datatable
DataTable BuildingTable = new DataTable();
DataTable DepartmentTable = new DataTable();
// Building Table
// get the column header means first line
string[] tempbuild = BuildingString[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in tempbuild)
{
BuildingTable.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < BuildingString.Length; i++)
{
string[] t = BuildingString[i].Split(',');
BuildingTable.Rows.Add(t);
}
// Department Table
// get the column header means first line
string[] tempdept = DepartmentString[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in tempdept)
{
DepartmentTable.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < DepartmentString.Length; i++)
{
string[] t = DepartmentString[i].Split(',');
DepartmentTable.Rows.Add(t);
}
// assign gridview datasource property by datatable
BuildingGrid.DataSource = BuildingTable;
BuildingGrid.DataBind();
BuildingGrid.Rows[0].Visible = false;
DepartmentGrid.DataSource = DepartmentTable;
DepartmentGrid.DataBind();
DepartmentGrid.Rows[0].Visible = false;
foreach (DataRow drb in BuildingTable.Rows)
{
BuildingDrop.Items.Add(new ListItem(drb[0].ToString(), drb[1].ToString()));
}
foreach (DataRow drd in DepartmentTable.Rows)
{
DepartmentDrop.Items.Add(new ListItem(drd[0].ToString(), drd[1].ToString()));
}
I am trying to parse the data in the first column of one ListView called raw and then if the data is correct, add that item to a second ListView called result.
However, when I go to run my program I get
the error:
"Cannot add or insert the item 'Collected' in more than one place.".
My Code
ListView result = new ListView();
for (int i = 0; i < raw.Items.Count; i++)
{
if (raw.Items[i].SubItems[0].Text.ToUpper() == "COLLECTED")
{
MessageBox.Show("confirm");
result.Items.Add(raw.Items[i]); // generating erros
}
}
printUsingLView(result);
clone original item:
result.Items.Add((ListViewItem)raw.Items[i].Clone());
or, if you want to make some adjustments
ListViewItem newItem = new ListViewItem();
newItem.Text = raw.Items[i].Text;
//enter other properties here and then add it to new listView
result.Items.Add(newItem);
I have a windows form application in c# where there are list of data in multiple listbox (around 56 in each listbox).
here is an example:
listbox1 contains data of name of students
listbox2 contains data of address of students
listbox3 contains percentage of students.
the list goes on with the student data.
Now i need to print the data in excel in a button click event.
the data should go in an ordered way .
I tried using the CSV helper but it only helped me for 1 set of list box i need to sent data from multiple list box.
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
foreach (var Name in lbx.Items)
{
csvWriter.WriteField(Name);
csvWriter.NextRecord();
}
foreach (var Address in ptr.Items)
{
csvWriter.WriteField(Address);
}
sw.Flush();
However, this doesn't solve the problem. Any help regarding the solution to this problem would be helpful.
Any other method to solve the problem will be great.
It's difficult for me to determine the full details of your configuration, but if it's as simple as two ListBox controls for which you're writing values, you could easily do something like the following:
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int lbxCount = lbx.Items.Count;
int ptrCount = ptr.Items.Count;
for (int i = 0; i < Math.Max(lbx.Items.Count, ptr.Items.Count); i++)
{
object lbxValue = lbxCount > i ? lbx.Items[i] : String.Empty;
object ptrValue = ptrCount > i ? ptr.Items[i] : String.Empty;
csvWriter.WriteField(lbxValue);
csvWriter.WriteField(ptrValue);
csvWriter.NextRecord();
}
sw.Flush();
sw.Close();
This determines the maximum number of records to write (Math.Max(lbx.Items.Count, ptr.Items.Count) based on the greatest ListBox.Items.Count.
By altering your loops to be a single loop, you can now use the WriteField method correctly. If the ListBox lbx does not contain a value for a certain record, it uses a String.Empty as the value for that record. Likewise it does the same for ListBox ptr, in the event that there are more items in lbx.
If you have many ListBox controls on a single form and wish to each of them, you could determine the maximum items overall by iterating through all ListBox controls and getting their respective Item.Count values as follows:
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int maxRecords = 0;
List<ListBox> listBoxes = new List<ListBox>();
// Add all ListBox controls to list
// Determine maximum number of items (in all ListBox controls)
foreach (Control control in Controls)
{
if (control.GetType() == typeof(ListBox))
{
ListBox currentListBox = (ListBox)control;
listBoxes.Add(currentListBox);
if (currentListBox.Items.Count > maxRecords)
maxRecords = currentListBox.Items.Count;
}
}
// Write fields for each ListBox
for (int i = 0; i < maxRecords; i++)
{
foreach (ListBox currentListBox in listBoxes)
{
if (currentListBox.Items.Count > i)
csvWriter.WriteField(currentListBox.Items[i]);
else
csvWriter.WriteField(String.Empty);
}
csvWriter.NextRecord();
}
sw.Flush();
sw.Close();
I have a listview in which the columns are dynamically created depending on the number of available subjects. When I create a new ListViewItem it automatically adds a blank subitem to the listview. Since the columns are dynamically created, the subitems are displaced. This is how I have done it.
foreach(int id in stud)
{
ListViewItem gtb = new ListViewItem();
foreach(int sname in subj)
{
gtb.SubItems.Add(value1);
gtb.SubItems.Add(value2);
gtb.SubItems.Add(value3);
}
gtb.SubItems.Add(value4);
listView1.Items.AddRange(new ListViewItem[] { gtb });
}
I know that adding the value1 to new ListViewItem(value1) would fix this but i have another subitem which is outside of the foreach loop. How can I fix this?
Add an 'if' statement that will check the length of each value then if the length is greater than zero you add the item to 'gtb'.
Create a String[], use it to collect your subitems, then create a new ListViewItem using that:
String[] subItems = new String[subj.Count + 1]; //add however many extras you need in place of 1
for (int j = 0; j < subj.Count; j++)
subItems[j] = subj[j];
//add whatever else to the array you want...
listView1.Items.Add(new ListViewItem(subItems));
I tried manually adding a new column which has a 0 width and it works just fine.
I would like to know how can I get a column name from a gridview? by its number not by name.
like : Name|Age|Birthday: ( so name=0 , age=1 etc...)
thanks.
You can get it like this :
gv.HeaderRow.Cells[i].Text
Or like this :
gv.Rows[0].Cells[i].Text
Rows[0] should be your header row.
//// Header column names
int gridViewCellCount = yourGridView.Rows[0].Cells.Count;
// string array to hold grid view column names.
string[] columnNames = new string[gridViewCellCount];
for (int i = 0; i < gridViewCellCount; i++)
{
columnNames[i] = ((System.Web.UI.WebControls.DataControlFieldCell)(yourGridView.Rows[0].Cells[i])).ContainingField.HeaderText;
}
simply
GridView1.Rows[0].Cells[0].Text;
try this if you want to all the cells value from each of the rows
foreach (GridViewRow r in GridView1.Rows)
{
string s = r.Cells[0].Text;
string y = r.Cells[1].Text;
}
update:
try this
foreach (TableCell Tc in GridView1.HeaderRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sssb = Tc.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
}
}
Revisiting this old question.... it's possible to get the field names of the data bound to a GridView with this kind of code. This makes a dictionary of colnum and field name.
private static IDictionary<int, string> GetGridViewFieldNames(object grid)
{
var names = new Dictionary<int, string>();
var view = grid as GridView;
if (view != null) {
for (var i = 0; i < view.Columns.Count; i++) {
var field = view.Columns[i] as BoundField;
if (field != null) {
names.Add(i, field.DataField);
}
}
}
return names;
}
This is not the answer to the question. It is only the answer if you never change the header text in the gridview. The asker of the question wanted to get the database field name by index.
I've seen a number of "answers" which only provide the text in the selected row of a gridview, or the header text which both do not answer the question that was asked...
You may ask why? If you were going to do audits of updates in a system and wanted to compare old values and new values and only update if they change and want to indicate which field was updated how do you show the database table field name at the index of the loop.
For instance:
Protected Sub gv_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
Dim intValCount As Integer = Integer.Parse(e.NewValues.Count)
If intValCount > 0 Then
Dim i As Integer = 0
For i = 0 To intValCount - 1
If Not e.OldValues(i).Equals(e.NewValues(i)) Then
' values have changed, audit the change
Sys.Audits.General(intID, "the_database_table", <the table field by index(i)>, e.OldValues(i).ToString, e.NewValues(i).ToString)
End If
i += 1
Next
End If
End Sub
So the questions is how do you get the database table field name by index via code behind? I too have been searching for this and all the "answers" that I've seen are not the answers I think some of us are really looking for. All the mentioned methods I've seen here are not bullet proof references to a database tables field name.
Its easy: Here i read the gridview header text for each header cell and add them as new columns to a data table.
DataTable dt = new DataTable();
foreach(DataControlFieldHeaderCell column in yourGridview.HeaderRow.Cells)
{
dt.Columns.Add(column.Text.Trim().Replace(" ", ""));
}
//Make sure you do all this after yourGridview.DataBind();
//If you do not want to bind data first simply bind an empty list like so:
/* yourGridview.DataSource = new List<string>();
yourGridview.DataBind(); */