.net - How to add controls dynamically? - c#

I want to add dynamic controls
Like the below image I want to do
I am struggling to do that
If I click Add More Experience button I want to display another rows
I tried with user control but it is not working properly.
Below code is working fine but if I add controls then close the browser page and then open the browser again added controls are coming.
I think the problem is static int i=0;
static int i = 0;
protected void addnewtext_Click(object sender, EventArgs e)
{
i++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
placeHolder.Controls.Add(ac);
placeHolder.Controls.Add(new LiteralControl("<BR>"));
}
}
Please provide your ideas? Thanks in advance

As per my comment, when using a static variable within an ASP.Net page, it will be shared amongst all users until the application pool or server is restarted.
Instead you should really be using a ViewState or similar to read/write the value.
private int controlCount
{
get
{
int val = 0;
try
{
val = (int)Page.ViewState["ControlCount"];
}
catch(Exception e)
{
// handle exception, if required.
}
return val;
}
set { Page.ViewState["ControlCount"] = value; }
}
protected void addnewtext_Click(object sender, EventArgs e)
{
int i = controlCount++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
placeHolder.Controls.Add(ac);
placeHolder.Controls.Add(new LiteralControl("<BR>"));
}
}

Related

datagrid get selected rows and cells values in wpf c#

I would like to redo the code of my old windows forms application on wpf and I have a problem with referencing datagridview.
This is the void look of my old application:
private void button2_Click(object sender, EventArgs e)
{
if (DGV1.Rows.Count > 0 && DGV1.SelectedRows != null)
{
bool wart = true;
for (int i = 0; i < listBox2.Items.Count; i++)
{
listBox2.SelectedIndex = i;
int w1 = Int32.Parse(listBox2.SelectedItem.ToString());
int w2 = Int32.Parse(DGV1.SelectedRows[0].Cells[0].Value.ToString());
if (w1 == w2)
{
wart = false;
break;
}
}
if (wart)
{
listBox2.Items.Add(DGV1.SelectedRows[0].Cells[0].Value);
}
}
}
This is the void look of my new application:
private void Button1_Click(object sender, RoutedEventArgs e)
{
IList rows = dataGrid1.SelectedItems;
if(dataGrid1.SelectedItem != null)
{
bool wart = true;
for (int i =0; i < listBox1.Items.Count; i++)
{
listBox1.SelectedIndex = i;
object item = dataGrid1.SelectedItem;
int w1 = Int32.Parse(listBox1.SelectedItem.ToString());
int w2 = Int32.Parse(dataGrid1.SelectedCells[0].Column.GetCellContent(item).ToString()); <--- !!
if(w1 == w2)
{
wart = false;
break;
}
}
if(wart)
{
listBox1.Items.Add(dataGrid1.SelectedCells[0]); <-- !!
}
}
}
The application spills out at the second if, where it displays:
And it should be:
Please Help :-)
It should probably be like this:
listBox1.Items.Add(dataGrid1.CurrentRow.Cells[0].Value);
This code is from WinForms, but I assume the coding for wpf may not be different, since both are in c#.
dataGrid1.SelectedItem isn't just some object, it has concrete type and properties like Id, Tytul, Kategorie, Text
you need to make a cast to that concrete type and access property instead of trying to get the value from low-level UI elements like DataGridCellInfo:
var item = (MyConcreteClass)dataGrid1.SelectedItem;
int w2 = item.Id;

c# comboBox updated by array in a method

I am fairly new to C#.
I trying to create a Combo Box that displays numbers from 1-100 generated from the method below. I am using an example that found on the internet and modifying it to meet my needs.
I can't get my combo box to display anything. Please offer suggestions or a better way to execute my intended goal.
private void Range()
{
ArrayList arr = new ArrayList();
for (int i = 0; i <= 100; i++)
{
arr.Add(i);
}
}
public void FillInComboBox(ComboBox target, int start, int end)
{
for(int i = start; i <= end; i++)
{
target.Items.Add(i);
}
}
Usage
private void Form2_Load(object sender, EventArgs e)
{
FillInComboBox(comboBox1, 0, 100);
}

Simulate CTRL down until I desire in c#?

I'm trying to simulate a user pressing ctrl down, the main goal would be in a datagridview when I select something programarly (initially) I dont want the user to then change that selection if not just add on to it or subtract, just as if you were to hold ctrl + left mouse click. I have no idea where to even begin. I tried to create a selection change event conbined with logicals but that will cause an infinite loop since we would be selecting one by a user then the code change other and other etc infinitely triggering that event. Please help, I'm sort of new to coding. I also don't know how to determine whether a ctrl key has been pressed, is pressed and being held.
private void selecttionh(object sender, EventArgs e)
{
if (stage == "4A" || stage == "3B" && ModifierKeys.HasFlag(Keys.Control))
{
int nothing = 0;
btnclickercl bt = new btnclickercl();
bt.dataGridView1_SelectionChanged(sender, e, dataGridViewReslist, dataGridViewnewres, nothing);
}
if (stage == "4A" || stage == "3B" && (ModifierKeys & Keys.Control) != Keys.Control)
{
MessageBox.Show("Please Press and hold " + "'ctrl'" + " to continue");
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
else
{
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
}
The way to make this happen is to store the selection state separately, update it when the user clicks a cell, then re-apply it. This prevents the selection from being lost every time they click. If you hook the proper event handlers (mouseup, not click) you can do this without the screen flickering and otherwise being a mess to look at.
Everything you need is in this class, including an extension method SetupToggledSelectionMode(), which is your entry point.
static public class Example
{
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new bool[rowCount][];
for (var r = 0; r < rowCount; r++)
{
result[r] = new bool[columnCount];
for (var c = 0; c < columnCount; c++)
{
var cell = input.Rows[r].Cells[c];
result[r][c] = cell.Selected;
}
}
return result;
}
static private void SetSelectionState(DataGridView input, bool[][] selectionState)
{
for (int r = 0; r <= selectionState.GetUpperBound(0); r++)
{
for (int c = 0; c <= selectionState[r].GetUpperBound(0); c++)
{
input.Rows[r].Cells[c].Selected = selectionState[r][c];
}
}
}
static public void SetupToggledSelectionMode(this DataGridView input)
{
bool[][] selectionState = GetSelectionState(input); //This will be stored in a closure due to the lambda expressions below
input.CellMouseUp += (object sender, DataGridViewCellMouseEventArgs e) =>
{
selectionState[e.RowIndex][e.ColumnIndex] = !selectionState[e.RowIndex][e.ColumnIndex];
SetSelectionState(input, selectionState);
};
input.SelectionChanged += (object sender, EventArgs e) =>
{
if (selectionState != null)
{
SetSelectionState(input, selectionState);
}
};
}
}
To use, populate your gridview, set up the initial selection programmatically, and call it like this:
myDataGrid.DataSource = myData;
myDataGrid.Refresh();
myDataGrid.SelectAll();
myDataGrid.SetupToggledSelectionMode();
The SetupToggledSelectionMode() method will register the necessary event handlers and store the selection state of the grid in a closed variable accessible to both handlers. So you won't have to declare anything additional; just call the method.
Thank you for this, this really helped me. all I did was to make it more efficient.Since it would call the Selection change every step of the way, so I got rid of that event completely and only kept the CellMouseup Event.
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new List<int[]>();
for (var r = 0; r < rowCount; r++)
{
for (var c = 0; c < columnCount; c++)
{
if(input.Rows[r].Cells[c].Selected==true)
{
result.add(new int[]{r,c});//will keep only the integer of selected items
}
}
}
return result;//this for me was a recycled variable it can be used or recycled from somewhere else
}
private void SetSelectionState(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
input.Rows[result[i][0]].Cells[result[i][1]].Selected = true;
}
}
public void SetupToggledSelectionMode(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
if(result[i].SequenceEqual(new int[] { e.RowIndex, e.ColumnIndex }))
{
result.RemoveAt(i);
continueer = 1;
break;
}
}
if (continueer == 0)
{
ResRoomSelections.Add(new int[] { e.RowIndex, e.ColumnIndex });
}
SetSelectionState(input);
//whatever else you need to do
}
I know there is still a better way to search List but I could not get a lamda search to work so I just used brute force
-Thank you John Wu for all

how to load groups in listView using Facebook SDK C#

I am using Facebook SDK c# to make windows application.
I try to load all page which I like it is successful.
The problem is when I press the load page button it load this data 1 more to become have duplicate, and get every page I like it 2 times
my code
private void button2_Click(object sender, EventArgs e)
{
string[,] friends;
FacebookClient fb = new FacebookClient(AppSettings.Default.AccessToken);
dynamic Grouplist = fb.Get("/me/likes");
int count = (int)Grouplist.data.Count;
friends = new string[count, 1];
for (int i = 0; i < count; i++)
{
listView3.Items.Add(Grouplist.data[i].name);
}
}
listView3.Items.Clear();
for (int i = 0; i < count; i++)
{
listView3.Items.Add(Grouplist.data[i].name);
}

How can I invert the selected items in multiple listboxes using only one for loop?

I am using three list boxes. I have to invert the selected items in all the list boxes using an invert button.
How can code it using only a single loop? There can be more than 3 list boxes as well.
Hi you could use this function to invert the selection for a given listbox.
/* Windows ListBox
public void InvertSelection(ListBox objLstbox)
{
if(objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.SetSelected(i, !objLstbox.GetSelected(i));
}
*/
//WebApp listbox
public void InvertSelection(ListBox objLstbox)
{
if (objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.Items[i].Selected = !objLstbox.Items[i].Selected;
}
private void btnInvert_Click(object sender, EventArgs e)
{
InvertSelection(listBox1);
InvertSelection(listBox2);
InvertSelection(listBox3);
}
public void InvertSelection(ListBox objLstbox)
{
if (objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.Items[i].Selected = !objLstbox.Items[i].Selected;
}
protected void Button1_Click(object sender, EventArgs e)
{
InvertSelection(ListBox1);
}
I banged my head on this with the rest of you, and finally developed my own function for Inverting
Here's the VB.Net Answer:
Private Function InvertListBoxSelections(ByRef tempListBox As ListBox) As Integer
Dim selectedind(tempListBox.SelectedItems.Count) As Integer
Try
For selind = 0 To tempListBox.SelectedItems.Count - 1
selectedind.SetValue(tempListBox.Items.IndexOf(tempListBox.SelectedItems(selind)), selind)
Next
tempListBox.ClearSelected()
For listitemIndex = 0 To tempListBox.Items.Count
If Array.IndexOf(selectedind, listitemIndex) < 0 Then
tempListBox.SetSelected(listitemIndex, True)
End If
Next
Return 1
Catch ex As Exception
Return 0
End Try
End Function
for (int i = 0; i < listbox.Items.Count; i++)
{
if (listbox.SelectedItems.Contains(listbox.Items[i]))
listbox.SetSelected(i, false);
else
listbox.SetSelected(i, true);
}
Since I got here and got confused by selection i'll leave this here.
This code inverts all checked items by using .SetItemChecked and .GetItemChecked:
private void ButtonInvertChecked_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox.Items.Count; i++)
checkedListBox.SetItemChecked (i, !checkedListBox.GetItemChecked(i));
}

Categories

Resources