how to create multiple column tree view with image - c#

i have a problem. i am using the BrightIdeasSoftware.TreeListView to create treeview in my windows form and i also take the reference of How to create a MultiColumn treeview like this in C# Winforms app but i am not success to create this. Can you please tell me what i am doing mistake to create the treeview. The complete description is below.
i want to add the dynamic collapsible Panel and into this want to add tree in this.
The data will display into the panel according the collapsible panel header id .
i have a parent id and that can have multiple child.
Status Column will display one image
below is my code that i am using to create the treeview
class Node
{
public string Name { get; private set; }
public string Column1 { get; private set; }
public string Column2 { get; private set; }
public List<Node> Children { get; private set; }
public Node(string name, string col1, string col2)
{
this.Name = name;
this.Column1 = col1;
this.Column2 = col2;
this.Children = new List<Node>();
}
}
private void InitializeFristTabValue()
{
if (_UserDAC == null)
_UserDAC = new UserDAC();
try
{
DataTable dtUserGroup = _UserDAC.GetAllSECGROUPS(appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
CommonDataGridBind cc = new CommonDataGridBind();
cc.GridviewGrouping(dtUserGroup, kryptonOutlookGridUserGroup, true, "GROUPID");
DataTable SEC_Info = _UserDAC.GetSECAPPINFO(appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
int Location = 0;
foreach (DataRow dtrow in SEC_Info.Rows)
{
int APPID;
int.TryParse(dtrow["APPID"].ToString(), out APPID);
collapsiblePanelobj = new CollapsiblePanel();
if (Location == 0)
{
collapsiblePanelobj.Collapse = false;
//collapsiblePanelobj.Dock = System.Windows.Forms.DockStyle.Fill;
this.collapsiblePanelobj.Size = new System.Drawing.Size(1000, 150);
//DataTable SEC_InfoTreeView = _UserDAC.GetAPPITEMSbyAPPID(APPID, appDirectory, this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
// ADDNode(APPID);
treeListView1.Dock = System.Windows.Forms.DockStyle.Fill;
//_panelBox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left;
//_panelBox.Controls.Add(treeListView1);
//collapsiblePanelobj.Controls.Add(_panelBox);
collapsiblePanelobj.Controls.Add(treeListView1);
}
else
collapsiblePanelobj.Collapse = true;
Location = Location + 30;
collapsiblePanelobj.Name = dtrow["APPNAME"].ToString() + dtrow["APPID"].ToString();
collapsiblePanelobj.HeaderText = "PROGRAM: " + dtrow["APPNAME"].ToString();
collapsiblePanelobj.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
collapsiblePanelobj.BackColor = System.Drawing.Color.Transparent;
collapsiblePanelobj.HeaderCornersRadius = 5;
collapsiblePanelobj.HeaderFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
collapsiblePanelobj.HeaderImage = null;
collapsiblePanelobj.HeaderTextColor = System.Drawing.Color.Black;
collapsiblePanelobj.Location = new System.Drawing.Point(10, Location);
collapsiblePanelobj.RoundedCorners = true;
//this.collapsiblePanelobj.Dock = System.Windows.Forms.DockStyle.Fill;
this.collapsiblePanelobj.Size = new System.Drawing.Size(1000, 150);
collapsiblePanelobj.UseAnimation = true;
InitializeData(APPID);
FillTree();
AddTree();
panel1.Controls.Add(collapsiblePanelobj);
// GrpBoxUserGroupInfo.Controls.Add(collapsiblePanelobj);
}
}
catch (Exception ex)
{
LogsWrite(ex, appDirectory, this.FindForm().Name, "InitializeFristTabValue()");
}
}
public void ADDNode()
{
AddTree();
InitializeData();
FillTree();
}
private void AddTree()
{
treeListView1 = new BrightIdeasSoftware.TreeListView();
treeListView1.Dock = DockStyle.Fill;
this.Controls.Add(treeListView1);
}
private void InitializeData()
{
UserDAC _UserDAC = new UserDAC();
DataTable SEC_InfoTreeView = _UserDAC.GetAPPITEMSbyAPPID(2, "", this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
data = new List<Node> {};
var parent1 = new Node("User Name ", "State ", "Static Caption ");
for (int i = 0; i < SEC_InfoTreeView.Rows.Count; i++)
{
int PrentID = Convert.ToInt32(SEC_InfoTreeView.Rows[i]["PARENTID"]);
if (PrentID == 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 0)
{
data.Add(parent1);
var parentAdd = new Node(Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"]));
parent1 = parentAdd;
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 2)
{
parent1.Children.Add(new Node(Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
}
}
private void FillTree()
{
// this.treeListView.SmallImageList = imageList1;
// set the delegate that the tree uses to know if a node is expandable
// treeListView1.Margin = new System.Windows.Forms.Padding(2, 1000, 2, 2);
treeListView1.CanExpandGetter = x => (x as Node).Children.Count > 0;
// set the delegate that the tree uses to know the children of a node
treeListView1.ChildrenGetter = x => (x as Node).Children;
// create the tree columns and set the delegates to print the desired object proerty
var nameCol = new BrightIdeasSoftware.OLVColumn("User Name", "Name");
nameCol.AspectGetter = x => (x as Node).Name;
nameCol.Width = treeListView1.Width / 3;
var col1 = new BrightIdeasSoftware.OLVColumn("State", "Column1");
col1.AspectGetter = x => (x as Node).Column1;
col1.Width = treeListView1.Width / 3;
var col2 = new BrightIdeasSoftware.OLVColumn("Static Caption", "Column2");
col2.AspectGetter = x => (x as Node).Column2;
col2.Width = treeListView1.Width / 3;
// add the columns to the tree
treeListView1.Columns.Add(nameCol);
treeListView1.Columns.Add(col1);
treeListView1.Columns.Add(col2);
// set the tree roots
this.treeListView1.Roots = data;
}
Thanks in advance for your help and comments

Related

How to bind dynamically created text box?

I'm trying to create pricelist for hotel. I'm having a list of dates, and list of room types in hotel. That lists can contain random number of elements. That is created dynamically, and here is the code:
private void CreateControls() { var colIndex = 0;
var vrsteSoba = _Presenter.VrstaSobeDto.ToArray();
foreach (var bindingItem in vrsteSoba)
{
var lbl = new Label()
{
Width = LABEL_WIDTH,
Height = LABEL_HEIGHT - 5,
Left = 10,
Top = 30 + colIndex * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL),
Text = bindingItem
};
_dataPanel.Controls.Add(lbl);
colIndex++;
}
int a = 1;
foreach (var date in _Presenter.CeneTarifa)
{
int y = 0;
var panel = new Panel
{
Height = PANEL_HEIGHT * (vrsteSoba.Length-4),
Width = EDIT_BOX_WIDTH,
Left = a * (EDIT_BOX_WIDTH + SPACE_BETWEEN_CONTROL + 50),
Top = 5
};
_dataPanel.Controls.Add(panel);
var label = new Label
{
Height = EDIT_BOX_HEIGHT,
Location = new Point(0, 10),
Text = date.Datum,
Margin = new Padding(0)
};
panel.Controls.Add(label);
int index = 0;
foreach (var item in date.VrstaSobeCena)
{
var box = new TextBox();
panel.Controls.Add(box);
box.Height = EDIT_BOX_HEIGHT;
box.Width = EDIT_BOX_WIDTH;
box.Location = new Point(0, 30 + y * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL));
box.DataBindings.Add(new Binding(nameof(box.Text), date, date.Cena[index].Cena1));
y++;
index++;
}
++a;
}
_dataPanel.AutoScroll = true;
}`
Here is image of that representation.
Now I'm facing a problem of data binding. I need to bind price, two way, for each text box. And I'm stuck.
I have tried to bind it to property name, but then all boxes get same value. If I try to bind it to value via index, I'm getting error
Cannot bind to the property or column 34 on the DataSource. Parameter name: dataMember
Code below is used to fill model that is used in presenter
` private void FillCenePoTarifi() { var sobeArr = VrstaSobeDto.ToArray();
foreach (var datum in Datumi)
{
var dictionary = new Dictionary<string, decimal>();
var cene = new List<Cena>();
foreach (var item in sobeArr)
{
var tarif = _Tarife.Where(x => x.SifTarife == item).FirstOrDefault();
if (tarif != null)
_SastavTarife = HotelierServerLocal.Default.TarifaViewBlo.GetSastaveTarife(tarif.IdTarife);
//proveriti ovu logiku
var cena = _SastavTarife.Where(x => x.Cena1 != 0).Select(c => c.Cena1).FirstOrDefault();
cene.Add(new Cena { Cena1 = cena.ToString()});
dictionary.Add(item, cena);
}
var model = new CenePoTarifi
{
Datum = datum,
VrstaSobeCena = dictionary,
Cena = cene
};
CeneTarifa.Add(model);
}
}`
Finally here are classes that use as model.
` public class CenePoTarifi{
public Dictionary<string, decimal> VrstaSobeCena { get; set; } = new Dictionary<string, decimal>();
public string Datum { get; set; }
private List<Cena> _Cena;
public List<Cena> Cena
{
get => _Cena;
set
{
_Cena = value;
NotifyPropertyChanged("Cena");
}
}
public class Cena :
{
private string _Cena1;
public string Cena1
{
get => _Cena1;
set
{
_Cena = value;
NotifyPropertyChanged("Cena1");
}
}
}`
Does anyone has any suggestions?
Your question is: How to bind dynamically created text box. Here is one tested way for accomplishing that specific task.
First create some textboxes dynamically:
public MainForm()
{
InitializeComponent();
buttonRandom.Click += (sender, e) => generateRandomList();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
List<TextBox> tmp = new List<TextBox>();
for (int column = 1; column < tableLayoutPanel.ColumnCount; column++)
{
for (int row = 1; row < tableLayoutPanel.RowCount; row++)
{
TextBox textBox = new TextBox { Anchor = (AnchorStyles)0xF };
tableLayoutPanel.Controls.Add(textBox, column, row);
tmp.Add(textBox);
textBox.KeyDown += onAnyTextBoxKeyDown;
}
}
_textboxes = tmp.ToArray();
// Generate first dataset
generateRandomList();
}
TextBox[] _textboxes = null;
Then, whenever a new random list is generated, clear any old text and databindings from every TextBox before creating a new data binding for it.
public static Random Rando { get; } = new Random(2);
private void generateRandomList()
{
// Clear ALL the data + bindings for ALL the textboxes.
foreach (var textbox in _textboxes)
{
textbox.Clear();
textbox.DataBindings.Clear();
}
// Generate and create new bindings
int count = Rando.Next(1, 79);
for (int i = 0; i < count; i++)
{
var textbox = _textboxes[i];
VrstaSobeCena vrstaSobeCena =
new VrstaSobeCena{ Sobe = (Sobe)tableLayoutPanel.GetRow(textbox) };
textbox.Tag = vrstaSobeCena;
textbox.DataBindings.Add(
new Binding(
nameof(TextBox.Text),
vrstaSobeCena,
nameof(VrstaSobeCena.Cena),
formattingEnabled: true,
dataSourceUpdateMode: DataSourceUpdateMode.OnPropertyChanged,
null,
"F2"
));
// TO DO
// ADD vrstaSobeCena HERE to the Dictionary<string, decimal> VrstaSobeCena
}
}
The classes shown in your code as binding sources may not bind correctly. One issue I noticed is that the property setters are failing to check whether the value has actually changed before firing the notification. Here's an example of doing that correctly. (For testing purposes I'm showing a Minimal Reproducible Sample "mock" version of a class that implements INotifyPropertyChanged.)
enum Sobe { APP4 = 1, APP5, STUDIO, SUP, APP6, STAND, STDNT, COMSTU, LUXSTU, APP4C, APP4L, APP62, APP6L }
class VrstaSobeCena : INotifyPropertyChanged
{
decimal _price = 100 + (50 * (decimal)Rando.NextDouble());
public decimal Cena
{
get => _price;
set
{
if (!Equals(_price, value))
{
_price = value;
OnPropertyChanged();
}
}
}
Sobe _sobe = 0;
public Sobe Sobe
{
get => _sobe;
set
{
if (!Equals(_sobe, value))
{
_sobe = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Finally, one way to test the two-way binding is to intercept the [Enter] key.
private void onAnyTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) && (sender is TextBox textbox))
{
e.SuppressKeyPress = e.Handled = true;
VrstaSobeCena vrstaSobeCena = (VrstaSobeCena)textbox.Tag;
string msg = $"Price for {vrstaSobeCena.Sobe} is {vrstaSobeCena.Cena.ToString("F2")}";
BeginInvoke((MethodInvoker)delegate {MessageBox.Show(msg); });
SelectNextControl(textbox, forward: true, tabStopOnly: true, nested: false, wrap: true);
}
}
Create a List for storing the textbox:
List<TextBox> lstTextbox = new List<TextBox>();
Create a class object that stores the values of "Date" and "room type"
public class RoomTypeDate
{
public string RoomType = "";
public string DateRange = "";
}
Immediately after you created the textbox, assigned the RoomTypeDate info to the tag, add it to lstTextbox.
foreach (var item in date.VrstaSobeCena)
{
var box = new TextBox();
panel.Controls.Add(box);
box.Height = EDIT_BOX_HEIGHT;
box.Width = EDIT_BOX_WIDTH;
box.Location = new Point(0, 30 + y * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL));
box.DataBindings.Add(new Binding(nameof(box.Text), date, date.Cena[index].Cena1));
// add the box to the list
lstTextbox.Add(box);
// mark the box with RoomType and DateRange
RoomTypeDate rtd = new RoomTypeDate();
rtd.RoomType = "APP4"; // get the room type
rtd.DateRange = "1.6 - 30.6"; // get date range
box.Tag = rtd;
y++;
index++;
}
Now, to get and set the room price:
public void SetRoomPrice(decimal price, string roomType, string dateRange)
{
foreach (var tb in lstTextBox)
{
var rtd = (RoomTypeDate)tb.Tag;
if(rtd.RoomType == roomType && rtd.DateRange == dateRange)
{
tb.Text = price.ToString();
return;
}
}
}
public decimal GetRoomPrice(string roomType, string dateRange)
{
foreach (var tb in lstTextBox)
{
var rtd = (RoomTypeDate)tb.Tag;
if(rtd.RoomType == roomType && rtd.DateRange == dateRange)
{
return Convert.ToDecimal(rt.Text);
}
}
return 0m;
}
*code untested, might contains bugs

Where is data updated in a DataGridView?

I am creating a tab page entirley programatically from a button press in the root page of a tabbed control. At present all the page initialisation takes place in the button click method. After all the instantiation, data capture from file and so on, I finally want to adjust the column widths in the data grid view, so that all the row data appears without having to have horizontal scroll bars. With the help of all your contributors I have managed to get it all working but the last step. Running at full speed it appears the DataGridView is accessed before the data load from the table is complete as it fails with an exception because the count derived from RegistersGrid.ColumnCount (local variable l) is zero. It all works fine if I step through the code. I am assuming that I need to put a Mutex of some form to wait for the transfer to complete, but I can't work out where that is taking place in order to reset the flag! If someone can point me in the right direction or if there is better more structured way to approach this I would deeply appreciate the help :-)
I have included all the code in the method just in case, I am afraid I date back a long way so if this looks like the awkward child of assembler,pascal and c with a little c# thrown in, my apologies....it's my age :-)
private void AddModuleButton_Click(object sender, EventArgs e)
{
string ModuleID = null;
string ModuleTypeFileNumber = null;
string ModuleType = null;
int TabID = 0;
openFileDialog1.Filter = "Text Files (.txt)|*.txt";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
string newline;
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split((char)9);
ModuleTypeFileNumber = values[1];
}
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split();
ModuleID = values[0];
ModuleType = values[1];
}
bool AbsorbLines = true;
while (AbsorbLines && ((newline = reader.ReadLine()) != null))
{
string[] values = newline.Split();
if (values[0] == "Readings") AbsorbLines = false;
}
string[] columnnames = { "Summary", "access", "register", "Module & Name", "Value", "unit", "type", "Res" };
string[] columntypes = { "System.Boolean", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.String", "System.String" };
int[] columnwidth = { 1,2,3,35,10,5,5,5 };
DataTable dt = new DataTable();
for(int i =0; i < columnnames.Length; i++)
{
DataColumn colString = new DataColumn(columnnames[i]);
colString.DataType = System.Type.GetType(columntypes[i]);
dt.Columns.Add(colString);
}
while (ImportTable("Controls", reader.ReadLine(), dt, "RO")) { } // Import the "readings" section
while (ImportTable("Status bits", reader.ReadLine(), dt, "RW")) { } // Import the "controls" section
reader.Close();
registerTables.Add(ModuleID, dt);
// create a new tab page
TabPage page = new TabPage(ModuleID);
InterbusRegisters.TabPages.Add(page);
//
// tabPage1
//
Button ResizeButton = new Button();
Button RemoveButton = new Button();
Label VersionLabel = new Label();
Label SerialNolabel = new Label();
TextBox VersionNoTB = new TextBox();
TextBox SerialNoTB = new TextBox();
DataGridView RegistersGrid = new DataGridView();
//
// Set the properties of the DataGrid.
//
RegistersGrid.AccessibleName = ModuleID + "Grid";
RegistersGrid.Location = new System.Drawing.Point(3,29);
RegistersGrid.Width = page.Width - 6;
RegistersGrid.Height = page.Height - 29;
RegistersGrid.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
RegistersGrid.DataSource = dt;
RegistersGrid.Dock = (DockStyle)2;
//
// RemoveButtonRegistersGrid
//
RemoveButton.BackColor = System.Drawing.Color.Red;
RemoveButton.Location = new System.Drawing.Point(3, 4);
RemoveButton.Name = "RemoveButton";
RemoveButton.Size = new System.Drawing.Size(75, 25);
RemoveButton.TabIndex = 0;
RemoveButton.Text = "Remove";
RemoveButton.UseVisualStyleBackColor = false;
RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click);
//
// ResizeButton
//
ResizeButton.BackColor = System.Drawing.Color.DarkOrange;
ResizeButton.Location = new System.Drawing.Point(81, 4);
ResizeButton.Name = "ResizeButton";
ResizeButton.Size = new System.Drawing.Size(75, 25);
ResizeButton.TabIndex = 6;
ResizeButton.Text = "Resize";
ResizeButton.UseVisualStyleBackColor = false;
ResizeButton.Click += new System.EventHandler(this.ResizeButton_Click);
//
// SerialNolabel
//
SerialNolabel.AutoSize = true;
SerialNolabel.Location = new System.Drawing.Point(159, 10);
SerialNolabel.Name = "SerialNolabel";
SerialNolabel.Size = new System.Drawing.Size(53, 13);
SerialNolabel.TabIndex = 4;
SerialNolabel.Text = "Serial No:";
//
// SerialNoTB
//
SerialNoTB.Location = new System.Drawing.Point(215, 7);
SerialNoTB.Name = "SerialNoTB";
SerialNoTB.Size = new System.Drawing.Size(100, 20);
SerialNoTB.TabIndex = 1;
//
// VersionLabel
//
VersionLabel.AutoSize = true;
VersionLabel.Location = new System.Drawing.Point(318, 10);
VersionLabel.Name = "VersionLabel";
VersionLabel.Size = new System.Drawing.Size(45, 13);
VersionLabel.TabIndex = 5;
VersionLabel.Text = "Version:";
//
// VersionTB
//
VersionNoTB.Location = new System.Drawing.Point(366, 7);
VersionNoTB.Name = "VersionTB";
VersionNoTB.Size = new System.Drawing.Size(100, 20);
VersionNoTB.TabIndex = 2;
page.Controls.Add(ResizeButton);
page.Controls.Add(RemoveButton);
page.Controls.Add(VersionLabel);
page.Controls.Add(VersionNoTB);
page.Controls.Add(SerialNolabel);
page.Controls.Add(SerialNoTB);
page.Controls.Add(RegistersGrid);
page.Location = new System.Drawing.Point(4, 22);
page.Size = new System.Drawing.Size(716, 554);
page.TabIndex = 1;
page.UseVisualStyleBackColor = true;
page.Update(); // the following code fails
int k = dt.Columns.Count;
int l = RegistersGrid.ColumnCount;
for (int j = 0; j <= RegistersGrid.ColumnCount - 1; j++)
RegistersGrid.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
RegistersGrid.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
//datagrid has calculated it's widths so we can store them
for (int i = 0; i <= RegistersGrid.ColumnCount - 1; i++)
{
int colw = RegistersGrid.Columns[i].Width; //store autosized widths
RegistersGrid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; //remove autosizing
RegistersGrid.Columns[i].Width = colw; //set width to calculated by autosize
}
}
}

How to find specific dynamic control and get value

I am making student attendance system. I am creating dynamic control and assigning values from database. Now I want to know how to find desired dynamic control and how I will get value from it.
I don't know how I can find desired control using a foreach loop.
This is my code for creating dynamic controls.
public void genControl(StudentAttendence sta)
{
StudentAttendenceBSLDAL stabd = new StudentAttendenceBSLDAL();
List<string[]> liName = stabd.takStudent(sta);
counts = Convert.ToInt16(stabd.takStudent(sta).Count);
for (int i=0; i< stabd.takStudent(sta).Count;i++)
{
for(int j = 0; j<liName[i].Count();j++)
{
Label lblStudentname = new Label();
Label lblStId = new Label();
lblStId.Name = "lblStId"+i.ToString()+j.ToString();
lblStudentname.Name = "liName"+i.ToString()+j.ToString();
lblStId.AutoSize = true;
lblStudentname.AutoSize = true;
if (j==0)
{
lblStId.Text = liName[i][j].ToString();
}
if(j==1)
{
lblStudentname.Text = liName[i][j].ToString();
}
lblStId.AutoSize = true;
lblStudentname.AutoSize = true;
if (i == 1)
{
lblStId.Location = new Point(41, 229);
lblStudentname.Location = new Point(153, 7);
}
else
{
lblStId.Location = new Point(3, 7 + 20);
lblStudentname.Location = new Point(153, 7 + 20);
}
this.Controls.Add(lblStId);
panel1.Controls.Add(lblStudentname);
}
CheckBox cba = new CheckBox();
cba.Name = "cba" + i.ToString() ;
cba.Text = "A";
cba.AutoSize = true;
CheckBox cbp = new CheckBox();
cbp.Name = i.ToString() ;
cbp.Text = "P";
cbp.AutoSize = true;
CheckBox cbl = new CheckBox();
cbl.Name = "cbl" + i.ToString() ;
cbl.Text = "L";
cbl.AutoSize = true;
if (i == 1)
{
cbp.Location = new Point(590, 3);
cba.Location = new Point(631, 3);
cbl.Location = new Point(670, 3);
}
else
{
cbp.Location = new Point(590, 3 + 23);
cba.Location = new Point(631, 3 + 23);
cbl.Location = new Point(670, 3 + 23);
}
panel1.Controls.Add(cbp);
panel1.Controls.Add(cba);
panel1.Controls.Add(cbl);
}
}
This is button control event in which I am trying to find control and get it value.
private void button2_Click(object sender, EventArgs e)
{
StudentAttendence sta = new StudentAttendence();
StudentAttendenceBSLDAL stabd = new StudentAttendenceBSLDAL();
// List<string[]> liName = stabd.takStudent(sta);
for (int i=0;i<counts;i++)
{
CheckBox cbP = panel1.Controls.OfType<CheckBox>().FirstOrDefault(b => b.Name.Equals("cbp"+i.ToString()));
// Label stid = panel1.Controls.Find("lblStId" + i.ToString(), false).First() as Label;
if(!cbP.IsChecked)
{
MessageBox.Show("control found");
}
}
}
You can save your control list into a SortedList.
You can use this sorted list for further processing

Display Hierarchical Data with UltraWinGrid with some customized grid Appearance settings?

I have objects which looks like this:
public class ComponentProperty
{
public string Property { get; set; }
public object Value { get; set; }
public string DataType { get; set; }
public string PropertyKey { get; set; }
public string Unit { get; set; }
public string DependencyType { get; set; }
public object ListType { get; set; }
public List<ComponentProperty> Properties { get; set; }
}
I have information build over in the following form of BindingList where Output is:
public class ComponentPropertyList: BindingList<ComponentProperty>
{
}
Scenario:
List of Component Properties bind to a Infragistics Ultra WinGrid to generate Master- Detail View and i made following customization in Grid settings:
void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
ultraGrid1.DisplayLayout.Override.AllowColSizing = AllowColSizing.Synchronized;
e.Layout.Bands[0].Override.HeaderAppearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
ultraGrid1.DisplayLayout.Appearance.BackColor = Color.White;
ultraGrid1.DisplayLayout.Appearance.BackColor2 = Color.White;
ultraGrid1.DisplayLayout.Override.ActiveRowAppearance = null;
ultraGrid1.DisplayLayout.BorderStyle = UIElementBorderStyle.None;
ultraGrid1.DisplayLayout.Override.BorderStyleCell = UIElementBorderStyle.None;
ultraGrid1.DisplayLayout.Override.BorderStyleRow = UIElementBorderStyle.None;
ultraGrid1.DisplayLayout.Override.ColumnAutoSizeMode = ColumnAutoSizeMode.Default;
ultraGrid1.DisplayLayout.Bands[0].ColHeadersVisible = true;
ultraGrid1.DisplayLayout.Bands[0].Override.RowSelectors = DefaultableBoolean.False;
ultraGrid1.DisplayLayout.Bands[0].Columns[0].CellActivation = Activation.NoEdit;
ultraGrid1.DisplayLayout.Bands[0].Columns[1].CellActivation = Activation.AllowEdit;
//Infosys: Nikita - Added for #1143 - START
ultraGrid1.DisplayLayout.Bands[0].Columns["Unit"].CellActivation = Activation.NoEdit;
//Infosys: Nikita - Added for #1143 - END
ultraGrid1.DisplayLayout.Bands[0].Columns[1].CellAppearance.BorderColor = Color.Black;
ultraGrid1.DisplayLayout.Override.RowAppearance.TextVAlign = VAlign.Middle;
// e.Layout.Bands[0].Columns[1].Width = 90;
ultraGrid1.DisplayLayout.Scrollbars = Scrollbars.Automatic;
ultraGrid1.DisplayLayout.ScrollBounds = ScrollBounds.ScrollToFill;
ultraGrid1.DisplayLayout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
ultraGrid1.DisplayLayout.Bands[0].Columns[2].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[0].Columns[3].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[0].Columns[2].Hidden = true;
ultraGrid1.DisplayLayout.Bands[0].Columns[3].Hidden = true;
//ultraGrid1.DisplayLayout.Bands[0].Columns[Constants.Collevel].Hidden = true;
//ultraGrid1.DisplayLayout.Bands[0].Columns[Constants.ColID].Hidden = true;
//ultraGrid1.DisplayLayout.Bands[0].Columns[Constants.Colparentid].Hidden = true;
ultraGrid1.DisplayLayout.Bands[0].Columns["DependencyType"].Hidden = true;
ultraGrid1.DisplayLayout.Bands[0].Columns["ListType"].Hidden = true;
//ultraGrid1.DisplayLayout.Bands[0].Override.AllowColSizing = AllowColSizing.Synchronized;
ultraGrid1.DisplayLayout.BorderStyle = UIElementBorderStyle.Default;
//ultraGrid1.DisplayLayout.Bands[0].Columns[1].TabStop = false;
ultraGrid1.DisplayLayout.Bands[0].Columns[1].CellAppearance.BackColor = Color.White;
ultraGrid1.DisplayLayout.Bands[0].Columns["Value"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
ultraGrid1.DisplayLayout.Bands[0].Columns["Value"].ButtonDisplayStyle = Infragistics.Win.UltraWinGrid.ButtonDisplayStyle.Always;
ultraGrid1.DisplayLayout.Bands[0].Columns["Value"].CellAppearance.BackColor = Color.White;
ultraGrid1.DisplayLayout.Override.SupportDataErrorInfo = SupportDataErrorInfo.CellsOnly;
ultraGrid1.DisplayLayout.Bands[0].Columns[1].SupportDataErrorInfo = DefaultableBoolean.True;
ultraGrid1.DisplayLayout.Bands[0].Columns[0].Width = 200;
ultraGrid1.DisplayLayout.Bands[0].Columns["Value"].Width = 120;
ultraGrid1.DisplayLayout.Bands[0].Columns["Value"].TabIndex = 0;
ultraGrid1.DisplayLayout.Bands[0].Columns["Unit"].Width = 60;
for (int rowCount = 0; rowCount < ultraGrid1.Rows.Count; rowCount++)
{
UltraGridRow row = ultraGrid1.Rows[rowCount];
if (string.IsNullOrEmpty(Convert.ToString(row.Cells[1].Value)))
{
row.Cells[1].Appearance.BackColor = Color.White;
}
}
ultraGrid1.DisplayLayout.BorderStyle = Infragistics.Win.UIElementBorderStyle.Solid;
ultraGrid1.DisplayLayout.Override.BorderStyleCell = Infragistics.Win.UIElementBorderStyle.Solid;
ultraGrid1.DisplayLayout.Override.GroupByRowSpacingAfter = 0;
ultraGrid1.DisplayLayout.Override.GroupByRowSpacingBefore = 0;
ultraGrid1.DisplayLayout.Override.HeaderPlacement = HeaderPlacement.OncePerGroupedRowIsland;
if (ultraGrid1.DisplayLayout.Bands.Count > 1)
{
ultraGrid1.DisplayLayout.Bands[1].ColHeadersVisible = false;
ultraGrid1.DisplayLayout.Bands[1].Columns[2].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[1].Columns[3].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[1].Columns[0].CellActivation = Activation.NoEdit;
ultraGrid1.DisplayLayout.Bands[1].Columns[4].CellActivation = Activation.NoEdit;
ultraGrid1.DisplayLayout.Bands[1].Columns[2].Hidden = true;
ultraGrid1.DisplayLayout.Bands[1].Columns[3].Hidden = true;
ultraGrid1.DisplayLayout.Bands[1].Columns["DependencyType"].Hidden = true;
ultraGrid1.DisplayLayout.Bands[1].Columns["ListType"].Hidden = true;
ultraGrid1.DisplayLayout.Bands[1].Columns[0].Width = 120;
//ultraGrid1.DisplayLayout.Bands[1].Columns[0].TabStop = false;
ultraGrid1.DisplayLayout.Bands[1].Columns["Value"].Width = 180;
ultraGrid1.DisplayLayout.Bands[1].Columns["Value"].TabIndex = 0;
ultraGrid1.DisplayLayout.Bands[1].Columns["Unit"].Width = 60;
//ultraGrid1.DisplayLayout.Bands[1].Columns[Constants.ColUnit].TabStop = false;
ultraGrid1.DisplayLayout.Override.RowSelectors = DefaultableBoolean.False;
if (e.Layout.Bands[1].Columns.Exists(" ") == true)
{
ultraGrid1.DisplayLayout.Bands[1].Columns[" "].Width = 0;
}
if (e.Layout.Bands[1].Columns.Exists(" ") == false)
{
ultraGrid1.DisplayLayout.Bands[1].Columns.Add(" ");
ultraGrid1.DisplayLayout.Bands[1].Columns[" "].Header.VisiblePosition = 0;
ultraGrid1.DisplayLayout.Bands[1].Columns[" "].Width = 0;
}
if (ultraGrid1.DisplayLayout.Bands.Count > 2)
{
ultraGrid1.DisplayLayout.Bands[2].ColHeadersVisible = false;
ultraGrid1.DisplayLayout.Bands[2].Columns[2].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[2].Columns[3].AutoSizeMode = ColumnAutoSizeMode.None;
ultraGrid1.DisplayLayout.Bands[2].Columns[0].CellActivation = Activation.NoEdit;
ultraGrid1.DisplayLayout.Bands[2].Columns[4].CellActivation = Activation.NoEdit;
//ultraGrid1.DisplayLayout.Bands[2].Override.AllowColSizing = AllowColSizing.None;
ultraGrid1.DisplayLayout.Bands[2].Columns[2].Hidden = true;
ultraGrid1.DisplayLayout.Bands[2].Columns[3].Hidden = true;
ultraGrid1.DisplayLayout.Bands[2].Columns["DependencyType"].Hidden = true;
ultraGrid1.DisplayLayout.Bands[2].Columns["ListType"].Hidden = true;
ultraGrid1.DisplayLayout.Bands[2].Columns[0].Width = 200;
ultraGrid1.DisplayLayout.Bands[2].Columns["Value"].Width = 120;
ultraGrid1.DisplayLayout.Bands[2].Columns["Unit"].Width = 60;
ultraGrid1.DisplayLayout.Override.RowSelectors = DefaultableBoolean.False;
//ultraGrid1.DisplayLayout.Bands[2].Columns[0].TabStop = false;
ultraGrid1.DisplayLayout.Bands[2].Columns["Value"].TabIndex = 0;
//ultraGrid1.DisplayLayout.Bands[2].Columns[Constants.ColUnit].TabStop = false;
ultraGrid1.DisplayLayout.Bands[2].Columns["Value"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
ultraGrid1.DisplayLayout.Bands[2].Columns["Value"].ButtonDisplayStyle = Infragistics.Win.UltraWinGrid.ButtonDisplayStyle.
if (e.Layout.Bands[2].Columns.Exists(" ") == true)
{
ultraGrid1.DisplayLayout.Bands[2].Columns[" "].Width = 0;
}
if (e.Layout.Bands[2].Columns.Exists(" ") == false)
{
ultraGrid1.DisplayLayout.Bands[2].Columns.Add(" ");
ultraGrid1.DisplayLayout.Bands[2].Columns[" "].Header.VisiblePosition = 0;
ultraGrid1.DisplayLayout.Bands[2].Columns[" "].Width = 0;
}
}
}
e.Layout.Bands[0].Override.CellAppearance.BorderAlpha = Alpha.Transparent;
e.Layout.Bands[0].Override.SelectedCellAppearance.ForeColor = Color.Black;
e.Layout.Bands[0].Override.RowAppearance.BorderAlpha = Alpha.Transparent;
e.Layout.Bands[0].Override.CellAppearance.BackColorAlpha = Alpha.Transparent;
e.Layout.Bands[0].Columns[0].CellActivation = Activation.NoEdit;
e.Layout.Bands[0].Columns[1].CellActivation = Activation.NoEdit;
e.Layout.Bands[0].Columns[2].CellActivation = Activation.NoEdit;
ultraGrid1.DisplayLayout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
ultraGrid1.DisplayLayout.Bands[0].Override.RowSelectors = DefaultableBoolean.False;
ultraGrid1.DisplayLayout.Appearance.BackColor = Color.White;
//ultraGrid1.DisplayLayout.Override.AllowColSizing = AllowColSizing.None;
//ultraGrid1.DisplayLayout.Override.AllowRowLayoutColMoving = GridBagLayoutAllowMoving.None;
ultraGrid1.DisplayLayout.BorderStyle = UIElementBorderStyle.Solid;
ultraGrid1.DisplayLayout.Bands[0].Columns[1].ButtonDisplayStyle = Infragistics.Win.UltraWinGrid.ButtonDisplayStyle.Always;
ultraGrid1.DisplayLayout.TabNavigation = TabNavigation.NextCell;
if (e.Layout.Bands[0].Columns.Exists(" ") == true)
{
ultraGrid1.DisplayLayout.Bands[0].Columns[" "].Width = 0;
//ultraGrid1.DisplayLayout.Bands[0].Columns[" "].ColSpan = 3;
}
if (e.Layout.Bands[0].Columns.Exists(" ") == false)
{
ultraGrid1.DisplayLayout.Bands[0].Columns.Add(" ").DataType = typeof(bool);
ultraGrid1.DisplayLayout.Bands[0].Columns[" "].Header.VisiblePosition = 0;
ultraGrid1.DisplayLayout.Bands[0].Columns[" "].Width = 0;
// ultraGrid1.DisplayLayout.Bands[0].Columns[" "].ColSpan = 3;
ultraGrid1.DisplayLayout.Bands[0].Columns[" "].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
UltraGridColumn checkBox = ultraGrid1.DisplayLayout.Bands[0].Columns[" "];
}
foreach (UltraGridBand band in ultraGrid1.DisplayLayout.Bands)
{
band.HeaderVisible = false;
}
}
componentProperties collection may have N Level depending on values.
CompoentProperty 1
--------> SubProperty1
---------------->SubSubProperty1
---------------->SubSubProperty1
CompoentProperty 2
--------> SubProperty2
---------------->SubSubProperty2
---------------->SubSubProperty2
---------------------->SubSubProperty3
---------------------->SubSubProperty3
--------------------------->SubSubProperty NN
Problem:
Layout is not correct, there are lots of Banding after assigning DataSource to grid as ComponentProperties Class and Specified Column Size does not take any effect on it.
Previously, i was using datatable as datasource that need to replace with object data source. Is there any settings require to work with object datasources.
I got the some solution from Infragistics fourm, that some what solve the layout problem. As i inspected when i use IList then these settings work correct after setting the MaxBandDepth Property at the form load event.
// Load only upto two descendant bands. So even if the data source has more than 3 level
// deep hierarchy, the UltraGrid will only make use of first two levels and ignore the
// levels deeper than that.
this.ultraGrid1.DisplayLayout.MaxBandDepth = 3;
The problem that was occured was similar as asked in below thread:
First Column of Wingrid Extending too large when datasource is IList
By default, the grid synchronizes the column widths of every band. So
in a case like this where you have a recursive data source, there
are essentially an infinite number of bands and for each band the grid
indents a little bit. This means that the first column gets very big
in order to accommodate the indentation all the way down the
hierarchy. The grid limits you to 100 bands of depth by default,
but that still means 100 level of indentation.
So there are a number of ways you can handle this.
Set MaxBandDepth on the grid to a smaller value. I recommend a value
of between 5 and 8. This will give you pretty good performance on a
decent machine and most users probably won't drill down more than 5
levels, anyway. You could set AllowColSizing to Free. This will stop
the grid from synchronizing the column widths and allow each band's
columns to be sized independently.
References:
MaxBandDepth Changing After Datasource Set
MaxBandDepth is not being used when the datasource is set
Ultragrid Hierarchical DataSource with Multiple Level Paths
UltraGrid hierarchy

The name does not exist in the current context c#

I'm trying to bind data with a chart to display it. However when I'm trying to link one of the columns with one of the axis of the chart it comes up with "The name Column1 does not exist in the current context" error. Does anybody know what I'm doing wrong and how to fix it?
Here is my code:
namespace bike
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var col1 = new List<string>();
var col2 = new List<string>();
var col3 = new List<string>();
var col4 = new List<string>();
var Column1 = col1.Select<string, int>(q => Convert.ToInt32(q));
var Column2 = col2.Select<string, int>(q => Convert.ToInt32(q));
var Column3 = col3.Select<string, int>(q => Convert.ToInt32(q));
var Column4 = col4.Select<string, int>(q => Convert.ToInt32(q));
dataGridView1.Columns.Add("col1", "Heart Rate");
dataGridView1.Columns.Add("col2", "Speed");
dataGridView1.Columns.Add("col3", "Power");
dataGridView1.Columns.Add("col4", "Altitude");
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
int row = 0;
string line;
bool isInHRData = false;
while ((line = sr.ReadLine()) !=null)
{
if (!isInHRData)
{
if (line != "[HRData]")
continue;
isInHRData = true;
continue;
}
else if (line.StartsWith("[") && line.EndsWith("["))
break;
string[] columns = line.Split('\t');
if (columns.Length > 0)
col1.Add(columns[0]);
if (columns.Length > 1)
col2.Add(columns[1]);
if (columns.Length > 2)
col3.Add(columns[2]);
if (columns.Length > 3)
col4.Add(columns[3]);
/*col1.Add(columns[0]);
col2.Add(columns[1]);
col3.Add(columns[2]);
col4.Add(columns[3]);
*/
dataGridView1.Rows.Add();
for (int i = 0; i < columns.Length; i++)
{
dataGridView1[i, row].Value = columns[i];
}
row++;
}
int maxSpeed = Column2.Max();
maxSpeed = maxSpeed / 10;
string MaxSpeed = Convert.ToString(maxSpeed);
textBox1.Text = MaxSpeed;
double aveSpeed = Column2.Average();
aveSpeed = aveSpeed / 10;
aveSpeed = Math.Round(aveSpeed, 0);
string AveSpeed = Convert.ToString(aveSpeed);
textBox2.Text = AveSpeed;
double aveHeart = Column1.Average();
aveHeart = Math.Round(aveHeart, 0);
string AveHeart = Convert.ToString(aveHeart);
textBox3.Text = AveHeart;
int maxHeart = Column1.Max();
string MaxHeart = Convert.ToString(maxHeart);
textBox4.Text = MaxHeart;
int minHeart = Column1.Min();
string MinHeart = Convert.ToString(minHeart);
textBox5.Text = MinHeart;
double avePower = Column3.Average();
avePower = Math.Round(avePower, 0);
string AvePower = Convert.ToString(avePower);
textBox6.Text = AvePower;
int maxPower = Column3.Max();
string MaxPower = Convert.ToString(maxPower);
textBox7.Text = MaxPower;
double aveAltitude = Column4.Average();
aveAltitude = Math.Round(aveAltitude, 0);
string AveAltitude = Convert.ToString(aveAltitude);
textBox8.Text = AveAltitude;
int maxAltitude = Column4.Max();
string MaxAltitude = Convert.ToString(maxAltitude);
textBox9.Text = MaxAltitude;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
chart1.DataSource = dataGridView1;
chart1.Series["Series1"].XValueMember = Column1;
chart1.Series["Series1"].YValueMembers = "test";
chart1.DataBind();
}
}
}
You're declaring Column1 as a local variable within your (rather long) button1_Click method. If you want it to be part of the state of the object, which will make it available in button2_Click, you should declare it as an instance variable instead.
You might want to consider what will happen if button 2 is clicked before button 1 though.

Categories