Acces dynamically created controls from other method C# - c#

I'm trying to acces my dynamically created Textbox through the click of a button.
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
int aantal = Convert.ToInt32(tbAantalControl.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
As you can see, I have already tried to access the Textbox by a FindControl(), But this didn't work. I want the Textbox that has the same last value as the clicked TextBox, I'm trying to do this by cutting the string and paste that in a variable.
Please help.

First of all you are searching for TextBoxes with different names than you create them with (tbAantal... vs. tbaantal...). Together with a recursive Find method that would work.
Neither is that good practice nor is it fast.
Better
Rather than searching for controls by name each time you create them you should implement something that directly let's you retrieve the controls (via some identifier or similar, in your case: via productid).
For example:
Declare a Dictionary<int, TextBox> textBoxes as a local variable. In your loop, add textBoxes.Add(productid, tbAantal); right after your definition of tbAantal.
In btnBestel_Click you can then use this mapping to retrieve the correct TextBox via textBoxes[productid].
I am aware that you don't really have the productid defined in that context.
Instead of using btnname.Remove(0, 6), you should use the Buttons's Tag property and store the productid as extra metadata:
Back in your loop add btnBestel.Tag = productid; at the appropriate position. In btnBestel_Click you can then write textBoxes[(int)button.Tag].
Overall code in that case
Dictionary<int, TextBox> textBoxes = new Dictionary<int,TextBox>();
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
textBoxes.Add(productid, tbAantal);
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
btnBestel.Tag = productid;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = textBoxes[(int)button.Tag];
int aantal = Convert.ToInt32(tbAantalControl.Text);
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}

I am not sure you are giving valid control name for search. For checking you should apply break point on the line, to see if you are getting valid control name.
For searching your required control by name you should look into each parent control recursively. FindControl method can be used for the purpose.
Change this:
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
With this:
Control tbAantalControl = FindControl(this.Controls, "tbAantal" + btnname.Remove(0, 6));
Method that recursive find your required:
private Control FindControl(Control.ControlCollection controlCollection, string name)
{
foreach (Control control in controlCollection)
{
if (control.Name.ToLower() == name.ToLower())
{
return control;
}
if (control.Controls.Count > 0)
{
Control result = FindControl(control.Controls, name);
if (result != null)
{
return result;
}
}
}
return null;
}

Is there any reason why you can't just make tbAantal a form level variable and then reference that in the btnBestel_Click method?
var tbAantal = null;
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"].Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
tbAantal = new TextBox { Size = new Size(107, 20), Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
int aantal = Convert.ToInt32(tbAantal.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal) Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}

Related

Tulpep Notification Scrollbar

I have a C# application with a Tulpep/Notification-Popup-Window. I need to use the feature of scrollbar. however it wont show when I have a-lot of details to scroll in Notification-Popup. let say if I have 5 items in Notification-Popup the scroll will not visible and when exceeds of 5 it will show the scrollbar"
public void notifyCriticalItems()
{
string critical = "";
con.conDB.Open();
cmd = new MySqlCommand("Select count(*) from vwcriticalitems", con.conDB);
string count = cmd.ExecuteScalar().ToString();
con.conDB.Close();
int i = 0;
con.conDB.Open();
cmd = new MySqlCommand("Select * from vwcriticalitems", con.conDB);
dr = cmd.ExecuteReader();
while (dr.Read())
{
i++;
critical += i + ". " + dr["pdesc"].ToString() + Environment.NewLine;
}
dr.Close();
con.conDB.Close();
PopupNotifier popup = new PopupNotifier();
popup.Image = Properties.Resources.icons8_brake_warning_25px_1;
popup.ContentFont = new System.Drawing.Font("Tahoma", 8F);
popup.Size = new Size(400, 100);
popup.ShowGrip = false;
popup.HeaderHeight = 20;
popup.TitlePadding = new Padding(3);
popup.ContentPadding = new Padding(3);
popup.ImagePadding = new Padding(8);
popup.AnimationDuration = 1000;
popup.AnimationInterval = 1;
popup.HeaderColor = Color.FromArgb(252, 164, 2);
popup.Scroll = true;
popup.ShowCloseButton = false;
popup.TitleText = "CRITICAL ITEM(S)";
popup.ContentText = critical;
popup.Popup();
}
Please consider removing this line:
popup.Size = new Size(400, 100);
This will allow the popup to expand based on your content

Looping name into a listview C#

ListViewItem item = new ListViewItem();
string productname = "";
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
string queryssxxxqbb = "Select * from products where deleted='No'";
MySqlCommand cmdaaxxxqbb = new MySqlCommand(queryssxxxqbb, conn);
MySqlDataReader dataReaderxxxxxqbb = cmdaaxxxqbb.ExecuteReader();
while (dataReaderxxxxxqbb.Read())
{
productname = dataReaderxxxxxqbb["productname"].ToString();
string productprice = dataReaderxxxxxqbb["productprice"].ToString();
string picturelink = dataReaderxxxxxqbb["picturelink"].ToString();
try
{
this.imageList1.Images.Add(Image.FromFile(#"\\" +
Properties.Settings.Default.Local_Server +
"\\Documents\\Stock And Inventory Software\\Product Pictures\\" +
picturelink));
}
catch
{
this.imageList1.Images.Add(Properties.Resources.default_image);
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(100, 90);
this.listView1.LargeImageList = this.imageList1;
item.Text = productname;
}
conn.Close();
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
item.BackColor = Color.White;
item.ImageIndex = j;
listView1.Items.Add(item);
}
Can anyone help me out, i keep getting "Cannot add or insert the item 'productname' in more than one place. You must first remove it from its current location or clone it."
I am trying to add the product name to much the images in a while loop.
You are continuously changing the value of item.Text, then iterating over all the images, but adding the same item value.
using(var conn = new MySqlConnection())
{
var index = 0;
conn.ConnectionString = connString;
conn.Open();
string queryssxxxqbb = "Select * from products where deleted='No'";
MySqlCommand cmdaaxxxqbb = new MySqlCommand(queryssxxxqbb, conn);
MySqlDataReader dataReaderxxxxxqbb = cmdaaxxxqbb.ExecuteReader();
while (dataReaderxxxxxqbb.Read())
{
var productname = dataReaderxxxxxqbb["productname"].ToString();
var productprice = dataReaderxxxxxqbb["productprice"].ToString();
var picturelink = dataReaderxxxxxqbb["picturelink"].ToString();
try
{
this.imageList1.Images.Add(Image.FromFile(#"\\" +
Properties.Settings.Default.Local_Server +
"\\Documents\\Stock And Inventory Software\\Product Pictures\\" +
picturelink));
}
catch
{
this.imageList1.Images.Add(Properties.Resources.default_image);
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(100, 90);
this.listView1.LargeImageList = this.imageList1;
var item = new ListViewItem();
item.Text = productname;
item.BackColor = Color.White;
item.ImageIndex = index++;
listView1.Items.Add(item);
}
}

How can I Print label from database select result using loop

I've to say this first , I'm new to windows programming,
I have got a requirement to print a set of results getting from a search query. Each resulted row should be printed on individual labels . A sample result set is included in the query. What is the best way achieving this.The barcode column shown should printed as bar code and the other two columns should print above and below the label.
Normally we may have to print up to 500 labels in a single button click.
Below I've added the code I'm working with. In the page load event I'm passing the ID to load data for a specific item from database. But I need to make it automated with a selected list of items, not a single one.
Result set
public partial class PrintLabel : Form
{
string s_desc = "";
string s_date = "";
Image bCodeImage;
public PrintLabel()
{
InitializeComponent();
}
private void PrintLabel_Load(object sender, EventArgs e)
{
FillData(735);
}
private void Print_Click(object sender, EventArgs e)
{
ItemPrint();
this.Close();
}
void FillData(int ID)
{
string str = Properties.Settings.Default.ConW;
using (SqlConnection conn = new SqlConnection(str))
{
try
{
string query = "select item.ID+'-'+item.ItemLookupCode as Barcode,ExtendedDescription,GETDATE()+180 Expiry from Item where ID=" + ID + ";";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read())
{
GenerateBarcode(dtr[0].ToString());
s_desc = dtr[1].ToString();
s_date = dtr[2].ToString();
lblDescription.Text = s_desc;
lblExpiry.Text = s_date;
PBBarcode.Image = bCodeImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void GenerateBarcode(string _bCodeImage)
{
string barCode = _bCodeImage;
Bitmap bitmap = new Bitmap(barCode.Length * 60, 750);
using (Graphics grapics = Graphics.FromImage(bitmap))
{
Font ofont = new System.Drawing.Font("IDAHC39M Code 39 Barcode", 14);
PointF point = new PointF(2f, 2f);
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush white = new SolidBrush(Color.White);
grapics.FillRectangle(white, 0, 0, bitmap.Width, bitmap.Height);
grapics.DrawString("*" + barCode + "*", ofont, black, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
bCodeImage = bitmap;
}
}
private void ItemPrint()
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
lblDescription.Text = s_desc;
lblExpiry.Text = s_date;
PBBarcode.InitialImage = bCodeImage;
}
}
I've achieved it using the below code, posting as it may help some one in the future.
private void PrintLabelVal()
{
string str = Properties.Settings.Default.con;
SqlConnection Conn = new SqlConnection(str);
string query = " SELECT TempLotUpdate.Quantity,Item.BinLocation,Item.ItemLookupCode," +
" Item.ExtendedDescription,Item.LotNumber," +
" Item.ExpiryDate " +
" FROM TempLotUpdate" +
" INNER JOIN Item ON TempLotUpdate.ItemId = Item.ID" +
" WHERE TempLotUpdate.PONumber = '" + Globals.s_PON + "'; ";
int cnt = 0;
int var = 0;
SqlCommand cmd = new SqlCommand(query, Conn);
try
{
Conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
for (var i = 0; i < dt.Rows.Count; i++)
{
cnt = Convert.ToInt32(dt.Rows[i][0]);
var = Convert.ToInt32(dt.Rows[i][4]);
for (var j = 0; j < cnt; j++)
{
var = Convert.ToInt32(dt.Rows[i][4]);
print(var); // Passing Lot ID
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void print(int obj)
{
FillData(obj);
ItemPrint();
this.Close();
}
void FillData(int ID)
{
string str = Properties.Settings.Default.con;
using (SqlConnection conn = new SqlConnection(str))
{
try
{
string query = "SELECT ItemLookupCode BarCode,Description,ExpiryDate,BinLocation,Price " +
" FROM Item where ID = " + ID + ";";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read())
{
barCode = dtr[0].ToString();
s_desc = dtr[1].ToString();
s_date = dtr[2].ToString();
s_BinLoc = dtr[3].ToString();
s_Price = dtr[4].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void ItemPrint()
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
string _desc = s_desc;
var _g = e.Graphics;
_g.DrawString(_desc, new Font("Arial Black", 7), Brushes.Black, 5, 8);
string _bCode = "*"+barCode+"*";
var _f = e.Graphics;
_f.DrawString(_bCode, new Font("IDAHC39M Code 39 Barcode", 8), Brushes.Black, 4, 25);
string _BinLoc = s_BinLoc;
var _i = e.Graphics;
_i.DrawString(_BinLoc, new Font("Arial Narrow", 7), Brushes.Black, 5, 75);
string _date = "Exp: " + s_date.Substring(0, 10);
var _h = e.Graphics;
_h.DrawString(_date, new Font("Arial Narrow", 7), Brushes.Black, 45, 75);
string _Price = s_Price;
var _j = e.Graphics;
_j.DrawString(_Price, new Font("Arial Narrow", 7), Brushes.Black, 120, 75);
}

How to make my id declaration global or getting it from other method?

Hello Everyone, I have this code :
I declared this global :
FlowLayoutPanel PresPanel = new FlowLayoutPanel();
My InitPanel :
Label PresLabel = new Label();
PresLabel.Text = "PRESIDENT :";
PresLabel.AutoSize = true;
PresLabel.Location = new Point(30, 20);
PresLabel.Font = new Font(this.Font, FontStyle.Bold);
PresLabel.Font = new Font("Courier New", 18);
PresLabel.ForeColor = Color.Orange;
this.Controls.Add(PresLabel);
PresPanel.Size = new Size(630, 160);
PresPanel.Location = new Point(50, 50);
PresPanel.FlowDirection = FlowDirection.LeftToRight;
PresPanel.BorderStyle = BorderStyle.FixedSingle;
PresPanel.AutoScroll = true;
PresPanel.WrapContents = false;
Controls.Add(PresPanel);
Form_load :
InitPanel();
PresPanel.SuspendLayout();
BtnVote.CenterHorizontally();
try
{
string cmdText = "SELECT (FirstName + ' ' + MiddleName + ' ' + LastName) as FullName, " +
"imgPath as ImagePath, " + "id as GetID FROM TableVote WHERE Position='President'";
using (SqlCommand com = new SqlCommand(cmdText, sc))
{
if (sc.State != ConnectionState.Open) sc.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
AddRadioButton(reader.GetString(0), reader.GetString(1), reader.GetInt32(2));
}
reader.Close();
sc.Close();
PresPanel.ResumeLayout(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
My AddRadioButton :
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
radio.AutoSize = false;
radio.Size = new Size(150, 130);
radio.Image = new Bitmap(Image.FromFile(imagePath), 90, 90);
radio.TextImageRelation = TextImageRelation.ImageAboveText;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.ImageAlign = ContentAlignment.MiddleCenter;
radio.TextAlign = ContentAlignment.MiddleCenter;
radio.ForeColor = Color.LimeGreen;
radio.CheckedChanged += radio_CheckedChanged;
}
Now for my question, How do I get my getID from AddradioButton whenever i click each radiobutton? Thanks.. :)
You can use the Tag property:
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
//.....
radio.Tag = getID;
radio.CheckedChanged += radio_CheckedChanged;
}
//then in the CheckedChanged event handler
private void radio_CheckedChanged(object sender, EventArgs e){
RadioButton radio = sender as RadioButton;
int getID = (int) (radio.Tag ?? -1);//suppose -1 is an invalid ID which is used to indicate that there is not associated ID
//other code....
}

SQL Server CE reader problem, it doesn't want to read!

another sql problem of mine ..
this time the reader doesn't work properly ( I think so )
I use this code and I get only 1 record added and my db has 100`s of records ..
public void addPosts()
{
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\msgdb.sdf";
string sql;
PictureBox avaBox = new PictureBox();
PictureBox pictureBox1 = new PictureBox();
Button atBtn = new Button();
RichTextBox msgBox = new RichTextBox();
Panel panelz = new Panel();
DateTime dt = DateTime.Now;
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from posts", connection);
DataSet data = new DataSet();
adapter.Fill(data);
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = connection;
sql = "Select user_from,msg,avatar FROM posts";
cmd.CommandText = sql;
connection.Open();
SqlCeDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
string ava = reader.GetString(2);
string usrFrom = reader.GetString(0);
string messige = reader.GetString(1);
//
// groupBox1
//
panelz.Controls.Add(pictureBox1);
panelz.Controls.Add(atBtn);
panelz.Controls.Add(avaBox);
panelz.Controls.Add(msgBox);
panelz.Location = new System.Drawing.Point(0, 335);
panelz.Name = "panel"+ i;
panelz.Size = new System.Drawing.Size(335, 90);
panelz.TabIndex = 0;
panelz.TabStop = false;
//
// pictureBox1
//
pictureBox1.Dock = System.Windows.Forms.DockStyle.Right;
pictureBox1.Image = global::m23.Properties.Resources.post_area;
pictureBox1.Location = new System.Drawing.Point(58, 0);
pictureBox1.Name = "pictureBox1"+i;
pictureBox1.Size = new System.Drawing.Size(281, 99);
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
pictureBox1.TabIndex = 1;
pictureBox1.TabStop = false;
//
// atBtn
//
atBtn.AutoSize = true;
atBtn.BackgroundImage = global::m23.Properties.Resources.post_user;
atBtn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
atBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
atBtn.Location = new System.Drawing.Point(0, 62);
atBtn.Name = "atBtn"+i;
atBtn.Size = new System.Drawing.Size(28, 25);
atBtn.TabIndex = 2;
atBtn.UseVisualStyleBackColor = true;
//
avaBox.Location = new System.Drawing.Point(0, 0);
avaBox.Name = "avaBox"+i;
avaBox.Size = new System.Drawing.Size(53, 53);
avaBox.TabIndex = 4;
avaBox.TabStop = false;
avaBox.ImageLocation = "http://img.edno23.com/avatars/thumbs/" + ava;
//
msgBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
msgBox.Location = new System.Drawing.Point(76, 10);
msgBox.Name = "msgBox"+i;
msgBox.ReadOnly = true;
msgBox.BackColor = Color.White;
msgBox.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
msgBox.Size = new System.Drawing.Size(251, 68);
msgBox.TabIndex = 3;
msgBox.Text = messige;
msgBox.BringToFront();
//
CommonFlowPanel.Controls.Add(panelz);
}
connection.Close();
}
Thanks for the help in advance!
Put the declarations for the Panel and all the controls that go onto each panel inside your while loop. You're basically re-adding your once instance of Panel ("panelz") over and over again. What you want to do is create a new panel for each row, inside your while loop, along with new instances of each control that sits on the panel.

Categories