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.
Related
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
I am writing the data from the table to an Excel file. The first time it executes, it inserts the data into the table but does not make it into the file, but when the second, 3rd, 4th etc. the app is executed, it writes to the file, and I am not seeing why it doesn't immediately after the first execution.
using (ExcelPackage excelPackage = new ExcelPackage())
{
// the query or stored procedure name for the database
string sqlQuery = "SELECT [PerDiemEntityId], [TripNumber] as [Trip #] ,[CustomerReferenceNumber] as [Customer Reference Number] ,[CustomerLocation] as [Customer Location] ,[EquipmentNumber] as [Equipment] ,[ArrivalTimeActual] as [Arrival Time Actual] ,[LastFreeDate] as [Last Free Date],[EquipmentAvailableDate] as [Equipment Available Date],[EquipmentChargeableDays] as [Equipment Chargeable Days],[PerDiemEquipmentChargeAmount] as [Equipment Charge Amt],[StorageChargeableDays] as [Storage Chargeable Days] ,[StorageChargeAmount] as [Storage Chargeable Amt],[NotifyDate] as [Notify Date],[OutgateDate] as [Outgate Date],[DestinationId] as [Destination ID],[OriginId] as [Origin ID],[CustomerId] as [Customer ID] FROM[LogisticsPerDiem].[dbo].[PerDiemEntity]";
// create a datatable
DataTable dataTable = loadExternalDataSet(sqlQuery);
// create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
worksheet.Cells["A1:O1"].Style.Font.Bold = true;
worksheet.Column(1).Style.WrapText = true;
worksheet.Column(1).Width = 17;
worksheet.Column(2).Style.WrapText = true;
worksheet.Column(2).Width = 15;
worksheet.Column(3).Style.WrapText = true;
worksheet.Column(3).Width = 15;
worksheet.Column(4).Style.WrapText = true;
worksheet.Column(4).Width = 15;
worksheet.Column(5).Style.WrapText = true;
worksheet.Column(5).Width = 15;
worksheet.Column(6).Style.WrapText = true;
worksheet.Column(6).Width = 15;
worksheet.Column(7).Style.WrapText = true;
worksheet.Column(7).Width = 15;
worksheet.Column(8).Style.WrapText = true;
worksheet.Column(8).Width = 15;
worksheet.Column(9).Style.WrapText = true;
worksheet.Column(9).Width = 15;
worksheet.Column(10).Style.WrapText = true;
worksheet.Column(10).Width = 15;
worksheet.Column(11).Style.WrapText = true;
worksheet.Column(11).Width = 15;
worksheet.Column(12).Style.WrapText = true;
worksheet.Column(12).Width = 15;
worksheet.Column(13).Style.WrapText = true;
worksheet.Column(13).Width = 15;
worksheet.Column(14).Style.WrapText = true;
worksheet.Column(14).Width = 15;
worksheet.Column(15).Style.WrapText = true;
worksheet.Column(15).Width = 15;
worksheet.Column(16).Style.WrapText = true;
worksheet.Column(16).Width = 15;
worksheet.Column(17).Style.WrapText = true;
worksheet.Column(17).Width = 15;
worksheet.Column(6).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
worksheet.Column(7).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
// worksheet.Column(9).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
worksheet.Cells["J2:J10000"].Style.Numberformat.Format = "$#,##0.00";
worksheet.Cells["L2:L10000"].Style.Numberformat.Format = "$#,##0.00";
worksheet.Cells["G2:G10000"].Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
worksheet.Cells["H2:H10000"].Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
string filePath = "C:\\temp\\PerDiemCharges" + "09162019" + ".xlsx" ;
// Instead of converting to bytes, you could also use FileInfo
FileInfo fi = new FileInfo(filePath);
excelPackage.SaveAs(fi);
}
// method for retrieving data from the database and return it as a datatable
DataTable loadExternalDataSet(string sqlQuery)
{
DataTable dt = new DataTable();
// using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connectionstring))
{
try
{
adapter.Fill(dt);
}
catch
{
}
}
return dt;
}
No errors I look to see the results from the table inserted into the file when the app is executed
This question already has answers here:
The name '__o' does not exist in the current context
(6 answers)
Closed 6 years ago.
public void Button_Click(object sender, RoutedEventArgs e)
{
string stringConnectionString = null;
SqlConnection objSqlConnection;
SqlCommand objSqlCommand = new SqlCommand();
DataSet objDataSet = new DataSet();
string stringCommandText = string.Empty;
stringConnectionString = ("Data Source=192.161.0.0;Initial Catalog=kkh_final;Persist Security Info=True;User ID=xx;Password=yyyyyyy");
objSqlConnection = new SqlConnection(stringConnectionString);
objSqlConnection.Open();
objSqlCommand.Connection = objSqlConnection;
objSqlCommand.CommandType = CommandType.StoredProcedure;
objSqlCommand.CommandText = "PCL0105A0_MR_Patients";
}
public void clsPatients(DataRow objDataRow, string[] stringInfo, string stringCommandText)
{
SqlParameter[] objSqlParameter;
stringCommandText = "PCL0105A0_MR_Patients";
int intRowIndex;
DataSet objDataSet = new DataSet();
SqlCommand objSqlCommand = new SqlCommand();
SqlDataAdapter objSqlDataAdapter;
try
{
objSqlParameter = new SqlParameter[63];
objSqlParameter[0] = new SqlParameter("#p_BO_ID", "KKHG");
objSqlParameter[0].Value = stringInfo[0];
objSqlParameter[1] = new SqlParameter("#p_HRN_ID", "A00025");
objSqlParameter[1].Value = objDataRow["HRN_ID"].ToString();
objSqlParameter[2] = new SqlParameter("#p_Short_Name", "Gowtham");
objSqlParameter[2].Value = objDataRow["Short_Name"].ToString();
objSqlParameter[3] = new SqlParameter("#p_Gender", "Male");
objSqlParameter[3].Value = objDataRow["Gender"].ToString();
objSqlParameter[4] = new SqlParameter("#p_DOB", "05/06/1992");
objSqlParameter[4].Value = objDataRow["DOB"].ToString();
objSqlParameter[5] = new SqlParameter("#p_Street_Name1", "Moovendar Nagar");
objSqlParameter[5].Value = objDataRow["Street_Name1"].ToString();
objSqlParameter[6] = new SqlParameter("#p_Ph_No1", "9585188641");
objSqlParameter[6].Value = objDataRow["Ph_No1"].ToString();
objSqlParameter[7] = new SqlParameter("#p_VIP_Status", "Yes");
objSqlParameter[7].Value = objDataRow["VIP_Status"].ToString();
objSqlParameter[8] = new SqlParameter("#p_Death_Status", "Will");
objSqlParameter[8].Value = objDataRow["Death_Status"].ToString();
objSqlParameter[9] = new SqlParameter("#p_Trans_Status", "test");
objSqlParameter[9].Value = objDataRow["Trans_Status"].ToString();
objSqlParameter[10] = new SqlParameter("#p_Citizenship", "Indian");
objSqlParameter[10].Value = objDataRow["Citizenship"].ToString();
objSqlParameter[11] = new SqlParameter("#p_Adm_Date", "05/06/1992");
objSqlParameter[11].Value = objDataRow["Adm_Date"].ToString();
objSqlParameter[12] = new SqlParameter("#p_Ref_Case", "NA");
objSqlParameter[12].Value = objDataRow["Ref_Case"].ToString();
objSqlParameter[13] = new SqlParameter("#p_Blk", "");
objSqlParameter[13].Value = objDataRow["Blk"].ToString();
objSqlParameter[14] = new SqlParameter("#p_Level_No", "25");
objSqlParameter[14].Value = objDataRow["Level_No"].ToString();
objSqlParameter[15] = new SqlParameter("#p_Unit_No", "25");
objSqlParameter[15].Value = objDataRow["Unit_No"].ToString();
objSqlParameter[16] = new SqlParameter("#p_Street_Name2", "Geetha Nagar");
objSqlParameter[16].Value = objDataRow["Street_Name2"].ToString();
objSqlParameter[17] = new SqlParameter("#p_City", "Thanjavoor City");
objSqlParameter[17].Value = objDataRow["City"].ToString();
objSqlParameter[18] = new SqlParameter("#p_Geographical_Area", "Thanjavoor");
objSqlParameter[18].Value = objDataRow["Geographical_Area"].ToString();
objSqlParameter[19] = new SqlParameter("#p_District", "Thanjavoor");
objSqlParameter[19].Value = objDataRow["District"].ToString();
objSqlParameter[20] = new SqlParameter("#p_Country", "India");
objSqlParameter[20].Value = objDataRow["Country"].ToString();
objSqlParameter[21] = new SqlParameter("#p_Post_Code", "636111");
objSqlParameter[21].Value = objDataRow["Post_Code"].ToString();
objSqlParameter[22] = new SqlParameter("#p_Ph_No2", "8792188641");
objSqlParameter[22].Value = objDataRow["Ph_No2"].ToString();
objSqlParameter[23] = new SqlParameter("#p_Ph_No3", "9626222891");
objSqlParameter[23].Value = objDataRow["Ph_No3"].ToString();
objSqlParameter[24] = new SqlParameter("#p_Ph_No4", "");
objSqlParameter[24].Value = objDataRow["Ph_No4"].ToString();
objSqlParameter[25] = new SqlParameter("#p_Ph_No5", "");
objSqlParameter[25].Value = objDataRow["Ph_No5"].ToString();
objSqlParameter[26] = new SqlParameter("#p_Ph_No6", "");
objSqlParameter[26].Value = objDataRow["Ph_No6"].ToString();
objSqlParameter[27] = new SqlParameter("#p_Email", "gtusk55#gmail.com");
objSqlParameter[27].Value = objDataRow["Email"].ToString();
objSqlParameter[28] = new SqlParameter("#p_Death_Date", "05/06/2085");
objSqlParameter[28].Value = objDataRow["Death_Date"].ToString();
objSqlParameter[29] = new SqlParameter("#p_Discharge_Disposition", "");
objSqlParameter[29].Value = objDataRow["Discharge_Disposition"].ToString();
objSqlParameter[30] = new SqlParameter("#p_Long_Name", "");
objSqlParameter[30].Value = objDataRow["Long_Name"].ToString();
objSqlParameter[31] = new SqlParameter("#p_Remarks", "");
objSqlParameter[31].Value = objDataRow["Remarks"].ToString();
objSqlParameter[47] = new SqlParameter("#p_delmark", "");
objSqlParameter[47].Value = objDataRow["delmark"].ToString();
objSqlParameter[48] = new SqlParameter("#p_gw_status", "");
objSqlParameter[48].Value = objDataRow["gw_status"].ToString();
objSqlParameter[49] = new SqlParameter("#p_data_source", "");
objSqlParameter[49].Value = objDataRow["data_source"].ToString();
objSqlParameter[50] = new SqlParameter("#p_Created_At", "");
objSqlParameter[50].Value = objDataRow["data_source"].ToString();
objSqlParameter[51] = new SqlParameter("#p_Created_By", "");
objSqlParameter[51].Value = objDataRow["data_source"].ToString();
objSqlParameter[52] = new SqlParameter("#p_Created_On", "");
objSqlParameter[52].Value = objDataRow["data_source"].ToString();
objSqlParameter[53] = new SqlParameter("#p_Modified_At", "");
objSqlParameter[53].Value = objDataRow["data_source"].ToString();
objSqlParameter[54] = new SqlParameter("#p_Modified_By", "");
objSqlParameter[54].Value = objDataRow["data_source"].ToString();
objSqlParameter[55] = new SqlParameter("#p_Modified_On", "");
objSqlParameter[55].Value = objDataRow["data_source"].ToString();
objSqlParameter[56] = new SqlParameter("#p_Temp_ID", "");
objSqlParameter[56].Value = objDataRow["Temp_ID"].ToString();
objSqlParameter[57] = new SqlParameter("#p_Temp_Flg", "");
objSqlParameter[57].Value = objDataRow["Temp_Flg"].ToString();
objSqlParameter[58] = new SqlParameter("#p_Latest_HRN", "");
objSqlParameter[58].Value = objDataRow["Latest_HRN"].ToString();
objSqlParameter[59] = new SqlParameter("#p_Latest_HRN", "");
objSqlParameter[59].Direction = ParameterDirection.Output;
// objSqlParameter[60] = new SqlParameter("#p_error_code", "");
//objSqlParameter[60].Direction = ParameterDirection.Output;
objSqlParameter[60] = new SqlParameter("#p_error_msg", "");
objSqlParameter[60].Direction = ParameterDirection.Output;
objSqlParameter[61] = new SqlParameter("#p_result", "");
objSqlParameter[61].Direction = ParameterDirection.Output;
objSqlParameter[62] = new SqlParameter("#p_data_source", "");
objSqlParameter[62].Direction = ParameterDirection.Input;
objSqlParameter[63] = new SqlParameter("#p_dml_indicator", "");
objSqlParameter[63].Value = objDataRow["dml_indicator"].ToString();
objSqlCommand.Parameters.AddRange(objSqlParameter);
objSqlDataAdapter = new SqlDataAdapter(objSqlCommand);
objSqlDataAdapter.Fill(objDataSet);
for (intRowIndex = 0; intRowIndex < objDataSet.Tables[0].Rows.Count - 1; intRowIndex++)
{
MessageBox.Show(objDataSet.Tables[0].Rows[intRowIndex][0].ToString());
}
}
Here this is my code, and tried lot, if i solve one error, another one will occur, here what is the problem to my code? i am going correct or not?
friends am new to this code field, so help me
thanks in advance friends
Ok, here's an example of how to create a connection, call a stored procedure and fill a dataset, which ultimately is what I think you're trying to achieve. You'll obviously need to tweak it for your data but hopefully this will get you on your way:
stringConnectionString = ("Data Source=192.161.0.0;Initial Catalog=kkh_final;Persist Security Info=True;User ID=xx;Password=yyyyyyy");
DataSet objDataSet = new DataSet();
using (SqlConnection connection = new SqlConnection(stringConnectionString))
{
SqlCommand cmd = new SqlCommand("dbo.MyProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pdParam = new SqlParameter("#YourParam", SqlDbType.VarChar);
pdParam.Value = pd;
cmd.Parameters.Add(pdParam);
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
da.Fill(objDataSet);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
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();
}
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;