Trying to display default selected value from ListView - c#

When I select a particular item in ListView item, I am able to display that particular item, and when the form loads I am getting the last item displayed by default (say the 10th item). However, what I want is to display the first item by default. How can I do this? I tried to do something like
listView1.Items[1].Selected = true;
but it's not working:
public partial class GroupExmStart : Form
{
string[] totDisplayQsn = null;
string[] QAndA = null;
string[] words = null;
private List<Question> questions;
ListViewItem lvi;
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)//using this I am adding items to listview
{
lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
totDisplayQsn = new string[totQsn + 1];
}
int Quiz(List<Question> questions)//using this I a passing set of questions to be displayed
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
private void DisplayQuestion(Question question)//using this i am displaying questions
{
string Q = question.Text;
label5.Text = Q;
string OP1 = question.Option1;
string OP2 = question.Option2;
string OP3 = question.Option3;
string OP4 = question.Option4;
radioButton12.Text = OP4;
radioButton11.Text = OP4;
radioButton10.Text = OP4;
radioButton9.Text = OP4;
}
}
private void listView1_MouseClick(object sender, MouseEventArgs e)//using this i am selection particular item and displaying it
{
if (totDisplayQsn.GetLength(0) >= 0)
{
if (listView1.SelectedItems.Count > 0)
{
var q = Convert.ToInt16(listView1.SelectedItems[0].Text);
var selectedQuestion = questions[q-1];
DisplayQuestion(selectedQuestion);
}
}
}
Thanks in advance for any help.

Try this
listView1.SelectedItems[0].Focused = true;

To select the first item, access it by its zero based index. Place the code just after your items initialization code.
for (int kk = 1; kk <= totQsn; kk++)//using this I am adding items to listview
{
lvi = new ListViewItem();
lvi.Selected = false;
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
listView1.Items[0].Selected = true;
DisplayQuestion(questions[0]);
Remove the following code:
int Quiz(List<Question> questions)//using this I a passing set of questions to be displayed
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}

Ok try the below code:
ListViewItem foundItem = listView1.FindItemWithText("Select4", false, 0, true);
if (foundItem != null)
{
listView1.Items[foundItem.Index].Selected = true;
}
That's All.

Related

Populate TextBoxes from a List

I am trying to populate TextBoxes from a list. I have been able to populate ComboBoxes with comboList:
var comboList = new System.Windows.Forms.ComboBox[4];
comboList[0] = cmbSite1Asset;
comboList[1] = cmbSite2Asset;
comboList[2] = cmbSite3Asset;
comboList[3] = cmbSite4Asset;
List<CRCS.CAsset> assets = _rcs.Assets;
foreach (CRCS.CAsset asset in assets)
{
string id = asset.ID;
for (int i = 0; i < 4; ++i)
{
comboList[i].Items.Add(id);
}
}
But when I try and apply the same principle to TextBoxes
var aosList = new System.Windows.Forms.TextBox[8];
aosList[0] = txtAsset1;
aosList[1] = txtAsset2;
aosList[2] = txtAsset3;
aosList[3] = txtAsset4;
aosList[4] = txtAsset5;
aosList[5] = txtAsset6;
aosList[6] = txtAsset7;
aosList[7] = txtAsset8;
foreach (CRCS.CAsset asset in assets)
{
string id = asset.ID;
for (int n = 0; n < 8; ++n)
{
aosList[n].Items.Add(id);
}
}
TextBox does not like Items.Add ( aosList[n]Items.Add(id); )
I am looking fore a reference or guidance resolving this issue. Thanks!
You should use ComboBox for your problem,instead of iterating on each element,You simply use below lines to populate combobox.
comboList.DataSource=assets;
comboList.DisplayMember="ID";
comboList.ValueMember="ID";
However,if you want your values in TextBox,you can use TextBox.AppendText Method, but it will not work like ComboBox as it will contain texts+texts+texts, will not have indexes like ComboBox.
private void AppendTextBoxLine(string myStr)
{
if (textBox1.Text.Length > 0)
{
textBox1.AppendText(Environment.NewLine);
}
textBox1.AppendText(myStr);
}
private void TestMethod()
{
for (int i = 0; i < 2; i++)
{
AppendTextBoxLine("Some text");
}
}
A Combobox is a collection of items, and so has an Items property from which you can add/remove to change it's contents. A Textbox is just a control that displays some text value, so it has a Text property which you can set/get, and which denotes the string that is displayed.
System.Windows.Forms.TextBox[] aosList = new System.Windows.Forms.TextBox[8];
aosList[0] = txtAsset1;
aosList[1] = txtAsset2;
aosList[2] = txtAsset3;
aosList[3] = txtAsset4;
aosList[4] = txtAsset5;
aosList[5] = txtAsset6;
aosList[6] = txtAsset7;
aosList[7] = txtAsset8;
for (int n = 0; n < 8; ++n)
{
aosList[n].Text = assets[n].ID; // make sure you have 8 assets also!
}
int i = 1;
foreach (var asset in assets)
{
this.Controls["txtAsset" + i].Text = asset.ID;
i++;
}

Clear contents of specific listview columns?

This is how I currently add info to my listview:
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
int totItems = Seq3.Count - 1;
if (PercentPopTolerance1.Count - 1 > totItems) totItems = PercentPopTolerance1.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (Seq3.Count - 1 >= i) item1 = Seq3[i].ToString();
if (PercentPopTolerance1.Count - 1 >= i) item2 = PercentPopTolerance1[i].ToString();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
View of empty listview:
Now how would I clear the contents of any particular column? Say I want to add to column YYMM but before I do this, I want to clear that particular column. How would this be done?
You can clear column values like this
var items = listView1.Items;
foreach (ListViewItem item in items)
{
a.SubItems["YYWW"].Text = "";
}
You should specify a column by its name (a column corresponds to a subitem in a ListViewItem), note that this Name is not ColumnHeader.Name, I mean the corresponding ListViewSubItem.Name:
public void ClearColumn(string colName){
foreach(ListViewItem item in listView1.Items){
var cell = item.SubItems[colName];
if(cell != null) cell.Text = "";
}
}
The following code will work for ColumnHeader.Name passed in instead of ListViewSubItem.Name as the code above does:
public void ClearColumn(string columnHeaderName){
int i = listView1.Columns.IndexOfKey(columnHeaderName);
if(i == -1) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[i].Text = "";
}
}
You can try the following code to make it work for Text instead of Name:
public void ClearColumn(string colText){
if(listView1.Items.Count == 0) return;
var col = listView1.Columns.Cast<ColumnHeader>()
.Select((x,i)=>new{x,i})
.FirstOrDefault(a=>a.x.Text == colText);
if(col == null) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[col.i].Text = "";
}
}

Displaying Particular Item On listView1_MouseClick

In Quize method I am passing qestions which contains set of all my Questions to be displayed using DisplayQuestion(),Question is my Class, Problem is that I am getting only First Question displayed, how can I get them displayed when i click on listviewItem if suppose questionscontains 10 Questions,than in listviewItem I have displayed numbers(1 2 3 4 5 ....10),when i click on each number how do i display that particular Questiondisplyed on click and if not clicked how all Questions displayed one by one using timer
public partial class GroupExmStart : Form
{
string[] randomQsn = new string[totQsn + 1]; //totQsn is the total number of question for e.g.10
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
var questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
randomQsn = new string[totQsn + 1];
timer1.Interval = 1000; //1000ms = 1sec
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
int Quiz(List<Question> questions)
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
private void DisplayQuestion(Question question)
{
string Q = question.Text;
label5.Text = Q;
string OP1 = question.Option1;
string OP2 = question.Option2;
string OP3 = question.Option3;
string OP4 = question.Option4;
radioButton12.Text = OP1;
radioButton11.Text = OP2;
radioButton10.Text = OP3;
radioButton9.Text = OP4;
}
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (randomQsn.GetLength(0) >= 0)
{
if (listView1.SelectedItems.Count > 0)
{
//here how should i get That particular Question so that i can display it
//something like this ? //Convert.ToInt16(listView1.SelectedItems[0].SubItems[0].Text)
DisplayQuestion(question);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tik++;
if (tik == 60)
{
label1.Text = (Convert.ToInt16(label1.Text) - 1).ToString();
tik = 0;
}
}
}
Thanks for any help in advance
The following is what you are looking for. You must grab the text of the list view item and use that as the index of the question.
if (listView1.SelectedItems.Count > 0)
{
var q = Convert.ToInt16(listView1.SelectedItems[0].Text);
var selectedQuestion = questions[q - 1];
DisplayQuestion(selectedQuestion);
}
In order for this to work, modify your constructor to the following:
private List<Question> questions;
public partial class GroupExmStart : Form
{
string[] randomQsn = new string[totQsn + 1]; //totQsn is the total number of question for e.g.10
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
/// THIS IS MODIFIED //
questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
randomQsn = new string[totQsn + 1];
timer1.Interval = 1000; //1000ms = 1sec
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}

Replace Images at the Top of ImageList and ListView

I will load say 10 images in imagelist and list View. then later, I want to replace the first 5 (top 5 in the list). But The new images are always added at the bottom of the list in the display.
Initialize_ListView()
for (int i = 0; i < 10; i++)
{
AddItemTo_ListView(i);
}
Now I later use this code to replace the top 5
for (int i = 0; i < 5; i++)
{
ImageAndThumb imgObj = new ImageAndThumb(output);
Replace(imgObj , i)
}
private void Initialize_ListView()
{
this.imageList1.Images.Clear();
this.listView1.Clear();
this.listView1.View = View.SmallIcon;
this.imageList1.ImageSize = new Size(75, 80);
this.listView1.SmallImageList = this.imageList1;
}
private void AddItemTo_ListView(int index)
{
ImageAndThumb imgObj = new ImageAndThumb(output);
ImageAndThumbLst.Add(imgObj);
this.imageList1.Images.Add(ImageAndThumbLst[index].Thumb);
ListViewItem item = new ListViewItem();
item.ImageIndex = index;
this.listView1.Items.Add(item);
}
private void Replace(ImageAndThumb obj, int indx)
{
ImageAndThumbLst[indx] = obj;
this.imageList1.Images[indx] = ImageAndThumbLst[indx].Thumb;
ListViewItem item = new ListViewItem();
item.ImageIndex = indx;
this.listView1.Items[indx]=item;
}
For anyone making the same mistake, I was creating a new item in he replace function which is unnecessay. The new replace function should look like this
private void Replace(ImageAndThumb obj, int indx)
{
ImageAndThumbLst[indx] = obj;
this.imageList1.Images[indx] = ImageAndThumbLst[indx].Thumb;
listView1.Refresh();
}

C# reassigning array values(down one step ex 5-4) that are within an object during a event

Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);

Categories

Resources