在运行时,我正在查询访问表并将结果存储在数组中。例如,该访问表的数据结构是
SalespersonName ------ Item1Sold ----- Item2Sold ---------- Item3Sold
Mitch Boat Camera
Jason Car Shells
Mitch Eggs
Richard Coffee Bacon Beans
我想创建一个包含SalespersonName&的标签。在SalesPerson名称旁边创建一个文本框,该文本框将显示所有非空白的itemold字段。所以我想要的输出是
(label) Mitch (textbox) Boat (textbox) Camera
(label) Jason (textbox) car (textbox) shells
(label) Mitch (textbox) Eggs
(label) Richard (textbox) Coffee (textbox) bacon (tetbox) beans
如果值不为null,我无法弄清楚如何只生成文本框。我只能做所有或不做的事,而不是我所追求的。
添加以下所有内容的代码
string path = "A:\\Database1.mdb";
object oName = path;
System.Collections.Hashtable lookup = new System.Collections.Hashtable();
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + oName);
olecon.Open();
OleDbCommand command = new OleDbCommand("SELECT * FROM info", olecon);
dr = command.ExecuteReader();
while (dr.Read())
{
fields.Add(dr[0].ToString());
}
dr.Close();
foreach (string field in fields)
{
Label labelz = new Label();
labelz.Name = "labelz_" + index;
labelz.Text = label;
labelz.AutoSize = true;
labelz.Location = new Point(10, 30);
panel1.Controls.Add(labelz);
TextBox textboxes = new TextBox();
textboxes.Name = "txt_" + index;
textboxes.Location = new Point(10, 80);
textboxes.AutoSize = true;
panel1.Controls.Add(textboxes);
if (field != "")
{
panel1.SetFlowBreak(textboxes, true);
}
index++;
}
答案 0 :(得分:1)
您的代码没有添加所有组件。它在标签变量和文本框中添加带有文本的标签。我建议你将逻辑拆分为两部分:
如何做到(未经过测试的伪代码):
第一部分:
//data class
class Person
{
public string Name {get;set;}
public List<string> SoldItems {get;set;}
}
//fill data
List<Person> Persons = new List<Person>();
int itemColumnCount = 3;
while (dr.Read())
{
Person person = new Person();
person.SoldItems = new List<string>();
//Get person name
person.Name = dr.GetString(dr.GetOrdinal("personNameColumn"));
//Get sold items
for(int i = 1; i <= itemColumnCount; i++)
{
//lets say you have columns: ItemSoldColumn1, ItemSoldColumn2, ItemSoldColumn3 for example
string columnName = "ItemSoldColumn" + i;
//check if column value is not null
if(!dr.IsDBNull(dr.GetOrdinal(columnName)))
{
string soldItem = dr.GetString(dr.GetOrdinal(columnName));
//add to persons sold items list
person.SoldItems.Add(soldItem);
}
}
}
第二部分:
foreach(var person in Persons)
{
//create label and set text to persons name
//...
newLabel.Text = person.Name;
//add to panel or some kind of layout control
//here you will have only sold items which is not null in database
//so just loop through sold items list and create texboxes
foreach(var item in person.SoldItems)
{
//create textbox
newTextBox.Text = item;
//add to panel or some kind of layout control
}
}
P.S。考虑将数据库结构更改为人员 - &lt; SoldItems关系。