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);
}
}
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();
}
Hello Everyone! I have a problem displaying my images and information such as full name in my program. I have a for looped radiobutton and it counts as to how many candidates are running in a specific position. Example is "President".
Here is my code as of now :
cmd = new SqlCommand("SELECT COUNT(Position) FROM TableVote WHERE Position='" + "President" + "'", sc);
Int32 PresCount = (Int32)cmd.ExecuteScalar();
TxtPresCount.Text = PresCount.ToString();
//int lol = Convert.ToInt32(TxtPresCount.Text);
var panel = new FlowLayoutPanel();
panel.SuspendLayout();
panel.Size = new Size(600, 150);
panel.Location = new Point(50, 50);
panel.FlowDirection = FlowDirection.LeftToRight;
panel.AutoScroll = true;
panel.WrapContents = false;
this.Controls.Add(panel);
for (int i = 0; i < PresCount; ++i)
{
var radioButton = new RadioButton();
radioButton.Size = new Size(75, 75);
radioButton.CheckAlign = ContentAlignment.MiddleCenter;
radioButton.ImageAlign = ContentAlignment.MiddleCenter;
panel.Controls.Add(radioButton);
//radioButton.Image = Image.FromFile();
radioButton.ImageAlign = ContentAlignment.MiddleCenter;
radioButton.FlatStyle = FlatStyle.Flat;
}
panel.ResumeLayout();
as for the codes above, it counts all the President that is stored in the database. But my problem is, how do i put an image/Name that is stored in the database? Example i have 5 candidates running for the position of President, I want all the data to be in 5 radiobutton. How do i put the information into the radiobutton? Please help. :(
I add information using this code below :
sc.Open();
try
{
cmd = new SqlCommand("INSERT INTO TableVote (Position, FirstName, MiddleName, LastName, YearLevel, Course, SchoolYear, imgPath, imgImage) VALUES (#position, #firstname, #middlename, #lastname, #yearlevel, #course, #schoolyear, #imgpath, '" + _pb + "')", sc);
cmd.Parameters.AddWithValue("#position", _position);
cmd.Parameters.AddWithValue("#firstname", _firstname);
cmd.Parameters.AddWithValue("#middlename", _middlename);
cmd.Parameters.AddWithValue("#lastname", _lastname);
cmd.Parameters.AddWithValue("#yearlevel", _yearlevel);
cmd.Parameters.AddWithValue("#course", _course);
cmd.Parameters.AddWithValue("#schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("#imgpath", _imgpath);
int res = cmd.ExecuteNonQuery();
if(res > 0)
{
MessageBox.Show("Data Stored Successfully!");
FAdminSet._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
this is my database :
public partial class Form1 : Form {
public Form1(){
InitializeComponent();
//do this if you want to register the Load event handler using code
Load += Form1_Load;
}
FlowLayoutPanel panel = new FlowLayoutPanel();
private void InitPanel(){
panel.Size = new Size(600, 150);
panel.Location = new Point(50, 50);
panel.FlowDirection = FlowDirection.LeftToRight;
panel.AutoScroll = true;
panel.WrapContents = false;
Controls.Add(panel);
}
//Load event handler
private void Form1_Load(object sender, EventArgs e){
InitPanel();
panel.SuspendLayout();
string cmdText = "SELECT (FirstName + ' ' + MiddleName + ' ' + LastName) as FullName, " +
"imgPath as ImagePath 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.Close();
sc.Close();
panel.ResumeLayout(true);
}
}
private void AddRadioButton(string fullName, string imagePath){
RadioButton radio = new RadioButton {Text = fullName, Parent = panel};
radio.AutoSize = true;
radio.Image = new Bitmap(Image.FromFile(imagePath),75,75);
radio.TextImageRelation = TextImageRelation.ImageAboveText;
radio.CheckAlign = ContentAlignment.BottomCenter;
}
}
NOTE: I can see that you store 2 info involving images in your table, I think you should choose 1 of them, storing Image Path is easy, light-weight for your table but the info may be lost if your Image path hasn't pointed to the actual image anymore.
I have 1000 markers displayed on map which are retrieved from datagridview. Thats working fine but I want to display text as client name on these markers when clicked. is it possible to do that....
if (comboBox5.SelectedIndex == 4)//(REGION 1)
{
gMapControl1.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance; ;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
GMapOverlay markersOverlay = new GMapOverlay("VCS MAP");
gMapControl1.MaxZoom = 11;
gMapControl1.MinZoom = 1;
gMapControl1.Zoom = 1;
SqlDataReader myReader;
String Query = " SELECT top 200 Latitude,Longitude,client name FROM [ICPS].[dbo].[agreement latlongkir] where region ='5' ";
SqlConnection conDataBase = new SqlConnection(conString);
conDataBase.Open();
SqlCommand cmdDatabase = new SqlCommand(Query, conDataBase);
myReader = cmdDatabase.ExecuteReader();
gMapControl1.HoldInvalidation = true;
while (myReader.Read())
{
string Latitude = myReader["Latitude"].ToString();
string Longitude = myReader["Longitude"].ToString();
string ClientName = myReader["client name"].ToString();
gMapControl1.Position = new PointLatLng(float.Parse(Latitude), float.Parse(Longitude));
GMarkerGoogle marker = new GMarkerGoogle(gMapControl1.Position, GMarkerGoogleType.pink);
markersOverlay.Markers.Add(marker);
gMapControl1.Overlays.Add(markersOverlay);
marker.ToolTip = new GMapRoundedToolTip(marker);
marker.ToolTipText = myReader("ClientName");
}
}
Looks like your missing this. I have implemented something similar with no issue. I have some working code you can take a look at if this doesnt help.
marker.ToolTipMode = MarkerTooltipMode.Always;
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.