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
Related
I'm Trying read an exported file from my web with Oledb, but always get "External table is table is not in the expected format" on code OleDbConnection.open() . But when I try copy the values on that excel into new excel, my code is working with that the new one. Its weird right? I must move the values into new excel for read it
This my last code for export excel, I have been tried another code like make excel with htmlwriter and the result always same.
[HttpGet]
public ActionResult ExportToExcel()
{ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet
if (System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft) // Right to Left for Arabic lang
{
ExcelWorksheetView wv = ws.View;
wv.ZoomScale = 100;
wv.RightToLeft = true;
ws.PrinterSettings.Orientation = eOrientation.Landscape;
ws.Cells.AutoFitColumns();
}
else
{
ExcelWorksheetView wv = ws.View;
wv.ZoomScale = 100;
wv.RightToLeft = false;
ws.PrinterSettings.Orientation = eOrientation.Landscape;
ws.Cells.AutoFitColumns();
}
ws.Cells.AutoFitColumns();
DataTable dt = new DataTable(); // Read records from database here
var ReturID = (Int64)Session["ReturID"];
var Header = ReturService.GetHeader(ReturID, "");
List<Kino.ViewModel.psa_kino_retur_materialViewModel> test = new List<Kino.ViewModel.psa_kino_retur_materialViewModel>();
test = ReturService.GetTableRetur(ReturID);
var v = test.AsQueryable();
var Data = (from a in v select a).ToList().Select(
p => new
{
p.material_id,
p.material_name,
p.delivery_qty,
p.sales_unit,
p.retur_information
}
); ;
DataColumn[] cols = { new DataColumn("Material", typeof(string)),
new DataColumn("Material Name", typeof(string)), new DataColumn("Quantity", typeof(int)),
new DataColumn("Sales Unit", typeof(string)),new DataColumn("Order Reason", typeof(string)) };
dt.Columns.AddRange(cols);
foreach (var item in Data)
{
DataRow row = dt.NewRow();
row[0] = item.material_id;
row[1] = item.material_name;
row[2] = item.delivery_qty;
row[3] = item.sales_unit;
row[4] = item.retur_information;
dt.Rows.Add(row);
}
ws.Cells[2,1].LoadFromDataTable(dt, true); // Print headers true
ExcelWorksheet ws2 = pck.Workbook.Worksheets.Add("Sheet2");
ExcelWorksheet ws3 = pck.Workbook.Worksheets.Add("Sheet3");
HttpContext.Response.Clear();
HttpContext.Response.AddHeader("", "");
HttpContext.Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
HttpContext.Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
HttpContext.Response.ContentType = "application/text";
HttpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
HttpContext.Response.BinaryWrite(pck.GetAsByteArray());
HttpContext.Response.End();
return View();}
and this my code for read excel
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03.
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 and above.
conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
try
{
connExcel.Open();
}
catch (Exception)
{
throw;
}
try
{
DataTable Count = new DataTable();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(Count);
connExcel.Close();
connExcel.Open();
int CheckHeader = 2;
Boolean Stoplooping = false;
foreach (DataRow row in Count.Rows)
{
foreach (var item in row.ItemArray)
{
if (item.ToString()== "Material")
{
Stoplooping = true;
break;
}
}
if (Stoplooping==true)
{
break;
}
CheckHeader++;
}
cmdExcel.CommandText = "SELECT * From [" + sheetName + "A"+CheckHeader+":AA" + (Count.Rows.Count + 1).ToString() + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
}
catch (Exception)
{
ModelState.AddModelError("", "No Data Found");
}
}
}
}
this is my connection string for oled db
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'" />
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=2;'" />
I have a DataGridView which is populating data from every disk of my network splitted by partition. I want to insert it into my database, but I don't know how I can validate how many rows I have into the DataGridView.
This is the code I already have:
try
{
con = new OleDbConnection(cs.DBConn);
con.Open();
string queryInsert = #"INSERT INTO tblComputers
(Partition1Disk, Type1Disk, TotalSpace1Disk,
UseSpace1Disk, FreeSpace1Disk, PercentageUse1Disk, Partition2Disk, Type2Disk, TotalSpace2Disk,
UseSpace2Disk, FreeSpace2Disk, PercentageUse2Disk, Partition3Disk, Type3Disk, TotalSpace3Disk,
UseSpace3Disk, FreeSpace3Disk, PercentageUse3Disk,Partition4Disk, Type4Disk, TotalSpace4Disk,
UseSpace4Disk, FreeSpace4Disk, PercentageUse4Disk)
VALUES
(#Partition1Disk, #Type1Disk, #TotalSpace1Disk, #UseSpace1Disk, #FreeSpace1Disk, #PercentageUse1Disk,
#Partition2Disk, #Type2Disk, #TotalSpace2Disk, #UseSpace2Disk, #FreeSpace2Disk, #PercentageUse2Disk,
#Partition3Disk, #Type3Disk, #TotalSpace3Disk, #UseSpace3Disk, #FreeSpace3Disk, #PercentageUse3Disk,
#Partition4Disk, #Type4Disk, #TotalSpace4Disk, #UseSpace4Disk, #FreeSpace4Disk, #PercentageUse4Disk)";
cmd = new OleDbCommand(queryInsert);
cmd.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
cmd.Parameters["#Partition1Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type1Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace1Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace1Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace1Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse1Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition2Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type2Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace2Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace2Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace2Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse2Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition3Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type3Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace3Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace3Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace3Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse3Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition4Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type4Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace4Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace4Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace4Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse4Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
}
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw;
}
The problem is that some of the computers from my Network only have one partition and when it happens, the application will display an error saying that index is out of bounds. There is any validation that I can do to see when there is only one or a maximum of 4 rows into the DataGridView and depending on that insert a null into that column?
I've got a function to draw a line graph as shown below. The data points are obtained from a MySQL table. However, how can I number each data point in the x axis 1,2,3,4...?
In the example below, the query returns two results and the graph displays the two points so the graph should have 1 and 2 marked on the axis.
EDIT: Initial problem solved. However, for the example above, there are 2 data points but the max x value is 3. Is there a way of setting the maximum x value to equal the number of data points?
protected void chart(int moduleID)
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string comm = "SELECT * FROM scores WHERE test_id=0 AND module_id=#ModuleID AND user_id=#UserID";
MySqlCommand mySqlCommand = new MySqlCommand(comm, conn);
mySqlCommand.Parameters.Add(new MySqlParameter("#ModuleID", moduleID));
mySqlCommand.Parameters.Add(new MySqlParameter("#UserID", Session["UserID"]));
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
DataTable ds = new DataTable();
Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Title = "attempt no.";
Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;
try
{
conn.Open();
dataAdapter.Fill(ds);
if (ds.Rows.Count > 0)
{
Chart1.DataSource = ds;
Chart1.Series["Series1"].YValueMembers = "score";
Chart1.DataBind();
}
else
{
Chart1.Visible = false;
lblError2.Text = "No results found.";
}
}
catch
{
lblError.Text = "Database connection error. Unable to obtain data at the moment.";
}
finally
{
conn.Close();
}
}
There is problem with:
Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
You have disbled AxisX labels
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.labelstyle.enabled%28v=vs.110%29.aspx
I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
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.