Display pictures with their name from database in winforms? - c#

dataGridView1.DataSource = null;
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select Name, Picture from Employee ", myDatabaseConnection))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
Instead of using datagridview, How I can display the picture with their Name in the panel or other control from the database something like this format http://static.neatorama.com/images/2008-04/yearbook-project-robot-johnny.gif in win form?
For example I have 7 records in the database, the form will display 7 panels with picture and label. And when I click or select a panel it will dipslay more information such as Address, Contacts, Etc in a textBox. If the records in the database is too many to fit in the form there will be a vertical or horizontal scroll bar.

I suggest you to create the objects you need dynamically. You can use "Location" to position your object.
Example :
int cptx = 0;
int cpty = 0;
for(int i=0; i<ds.Tables[0].Rows.Count;i++)
{
PictureBox currentpic = new PictureBox();
Label currentlabel = new Label();
currentpic.Size = new Size(20,20);
currentlabel.Size = new Size(20,20);
currentpic.BorderStyle = BorderStyle.FixedSingle;
currentlabel.Text = "te";
if(cptx >= 4)
{
cptx = 0;
cpty ++;
}
currentpic.Location= new Point((cptx*25),(cpty*50));
currentlabel.Location = new Point((cptx*25),(cpty*50)+25);
This.Controls.Add(currentpic);
cptx ++;
}
This code should do this :
EDIT : I suggest you to take a look at the "User control", the user control allow you to create you own control. So, the picture and the label will be inside a single control. The advantage to use the user control is the control you will create will be totally reusable for your other windows and/or programs.

Form has only one panel (pnlGrid) and panel's AutoScroll property setted as true;
DataTable dtImage = new DataTable();
dtImage.Columns.Add("Path");
dtImage.Columns.Add("Name");
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
CreateImageGrid(dtImage);
and method;
private void CreateImageGrid(DataTable dtDataSource)
{
int colCount = 5;
int rowCount = 0;
int imgWidth = 100;
int imgHeight = 100;
int imgPadding = 10;
int lblPadding = 5;
int ind = -1;
PictureBox pic = null;
Label lbl = null;
if (dtDataSource.Rows.Count > colCount)
{
rowCount = Convert.ToInt32(dtDataSource.Rows.Count / colCount);
if (Convert.ToInt32(dtDataSource.Rows.Count % colCount) > 0)
{
rowCount++;
}
}
else
{
rowCount = 1;
}
for (int j = 0; j < rowCount; j++)
{
for (int i = 0; i < colCount && dtDataSource.Rows.Count > ((j * colCount) + i); i++)
{
ind = (j * colCount) + i;
pic = new PictureBox();
pic.Image = Image.FromFile(dtDataSource.Rows[ind]["Path"].ToString());
pnlGrid.Controls.Add(pic);
pic.Width = imgWidth;
pic.Height = imgHeight;
pic.Top = (j * (imgHeight + imgPadding)) + imgPadding;
pic.Left = (i * (imgWidth + imgPadding)) + imgPadding;
lbl = new Label();
lbl.Text = dtDataSource.Rows[ind]["Name"].ToString();
pnlGrid.Controls.Add(lbl);
lbl.Left = pic.Left;
lbl.Top = pic.Top + pic.Height + lblPadding;
}
}
}
Note: Text lengths may cause problems, you should define some rules.

Related

how to create dynamic button in c# windows application

i have two layutflowpanel
1-flowpanel_category
2-flowpanel_products
when i use nested for loop inside button click to get products from current select category another flowpanel_prd not showing that products from categorey maybe i have some mistake in the some point
i set inside InitialComponents this code to retrive all items from category to put it inside flowpanel_category
//get all category and set it all to flowpanel_cat
FLOWPANEL_CAT.Controls.Clear();
try
{
DT = clsgetcat.get_prd_categories();
for (int i = 0; i <= DT.Rows.Count; i++)
{
Extendedbutton Eb = new Extendedbutton();//with Extendedbutton this time
Eb.prdid = DT.Rows[i][0].ToString();//this asigns product_id to extended txtprdid
Eb._prdnme = DT.Rows[i][1].ToString();//this asigns product_nme to extended txtprdnme
Eb._myval = DT.Rows[i][1].ToString();//this asigns products to extended buttondescription
Eb.Name = DT.Rows[i][1].ToString();
Eb.Text = DT.Rows[i][1].ToString();
Eb.ForeColor = Color.White;
Eb.BackColor = Color.SkyBlue;
Eb.Font = new Font("Serif", 10, FontStyle.Regular);
Eb.Width = 100;
Eb.Height = 60;
Eb.TextAlign = ContentAlignment.MiddleCenter;
Eb.Margin = new Padding(5);
Button b = addbutton(i);
Eb.Click += new System.EventHandler(this.buttonclick);
FLOWPANEL_CAT.Controls.Add(Eb);
}
}
catch
{
return;
}
iset inside buttonclick this code to show each items from category inside flowpanel_prodcuts
public void buttonclick(object sender, EventArgs e)
{
FLOWPANEL_PRD.Controls.Clear();
for (int i = 0; i <= DT.Rows.Count; i++)
{
try
{
for (int j = 0; j <= i; j++)
{
Extendedbutton Eb = new Extendedbutton();//with Extendedbutton this time
Eb._prdid = DT.Columns[0].ToString();
string prdid = ((Extendedbutton)sender)._prdid;
Eb._prdnme = DT.Columns[1].ToString();
string prdnme = ((Extendedbutton)sender)._prdnme;
Eb.Name = DT.Rows[j][1].ToString();
Eb.Text = DT.Rows[j][1].ToString();
Eb.ForeColor = Color.White;
Eb.BackColor = Color.SkyBlue;
Eb.Font = new Font("Serif", 10, FontStyle.Regular);
Eb.Width = 100;
Eb.Height = 60;
Eb.TextAlign = ContentAlignment.MiddleCenter;
Eb.Margin = new Padding(5);
Button b = addbutton(j);
Eb.Click += new System.EventHandler(this.buttonclick);
txttotalamount.Clear();
txtprdqty.Clear();
txtprdqty.Focus();
FLOWPANEL_PRD.Controls.Add(Eb);
}
}
catch
{
return;
}
}
txtprdqty.Focus();
}
Button addbutton(int i)
{
Extendedbutton EB = new Extendedbutton();
EB.Name = EB._myval;
EB.Text = EB._myval;
EB.ForeColor = Color.White;
EB.BackColor = Color.SkyBlue;
EB.Font = new Font("Serif", 10, FontStyle.Regular);
EB.Width = 100;
EB.Height = 60;
EB.TextAlign = ContentAlignment.MiddleCenter;
EB.Margin = new Padding(5);
return EB;
}
this picture show you output result but i have some mistake when i get products from each category

How to get the values of button templatefield in Gridview?

I want to display the row details of Gridview when user click the button of template field. I got the output to display the button in a Gridview using template field. But when user click the button it reload the page and display the empty template with rows.
Full Coding of c#
string selectedColumn;
string[] splitSelectedColumn;
string groupByColumn;
string[] splitGroupByColumn;
ArrayList listBtnOrLbl = new ArrayList();
int compareFlag = 0;
protected void btnRefresh_Click(object sender, EventArgs e)
{
selectedColumn = txtColumnNames.Text;
splitSelectedColumn = selectedColumn.Split(',');
groupByColumn = txtGroupBy.Text;
splitGroupByColumn = groupByColumn.Split(',');
string[] compareGroup = new string[splitGroupByColumn.Length];
//Grouping column names using selected column text
int flag = 1;
foreach (string columnName in splitSelectedColumn)
{
flag = 1;
foreach (string groupByName in splitGroupByColumn)
{
if (columnName.Equals(groupByName))
{
flag = 2;
break;
}
}
if (flag == 1)
{
groupByColumn = groupByColumn + "," + columnName;
}
}
// CREATE A TEMPLATE FIELD AND BOUND FIELD
BoundField bfield = new BoundField();
TemplateField[] ttfield = new TemplateField[splitGroupByColumn.Length];
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
if (i < splitGroupByColumn.Length)
{
ttfield[i] = new TemplateField();
ttfield[i].HeaderText = splitGroupByColumn[i];
GridView1.Columns.Add(ttfield[i]);
}
else
{
try
{
bfield.HeaderText = splitSelectedColumn[i];
bfield.DataField = splitSelectedColumn[i];
Response.Write("<br/>BOUND FIELD==" + splitGroupByColumn[i]);
GridView1.Columns.Add(bfield);
}
catch (Exception)
{
}
}
}
// CREATE DATA TABLE and COLUMN NAMES
DataTable dt = new DataTable();
//dt.Columns.Clear();
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
dt.Columns.Add(splitSelectedColumn[i]);
//Console.WriteLine(splitSelectedColumn[i]);
System.Diagnostics.Debug.WriteLine(splitSelectedColumn[i]);
Response.Write("<br/>DT COLUMN NAMES==" + splitSelectedColumn[i]);
}
//ADD ROWS FROM DATABASE
string cs = ConfigurationManager.ConnectionStrings["connectionStringDB"].ConnectionString;
//int compareFlag = 0;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] where ItemLookupCode='" + txtItemLookupCode.Text + "'and ChildItemLookupCode1='" + txtChildItemLookupCode.Text + "' group by " + groupByColumn + " ";
cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] group by " + groupByColumn + " ";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
string addData = string.Empty;
string[] stackss = new string[splitSelectedColumn.Length];
while (rd.Read())
{
//SET the FIRST VALUES in `stackss[]` for comparing next values of rd[]
if (compareFlag == 0)
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
compareGroup[i] = rd[splitGroupByColumn[i]].ToString();
Response.Write("<br/>COMPARE GROUP [i]==" + compareGroup[i]);
}
compareFlag = 1;
Response.Write("<br/>splitSelectedColumn.LENGTH==" + splitSelectedColumn.Length);
Response.Write("<br/>STACK.LENGTH==" + stackss.Length);
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
for (int i = 0; i < compareGroup.Length; i++)
{
stackss[i] = compareGroup[i];
}
//TESTING PURPOSE ONLY
for (int i = 0; i < stackss.Length; i++)
{
//stack[i] = "";
Response.Write("<br/>STACK.VALUES==" + stackss[i]);
}
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("Execute BUTTON");
listBtnOrLbl.Add("button");
}
//stackss = new string[] { "" };
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
int tempValue = 0;
for (int i = 0; i < compareGroup.Length; i++)
{
if (compareGroup[i] == rd[i].ToString())
{
tempValue = tempValue + 1;
if (tempValue == compareGroup.Length)
{
for (int k = 0; k < splitSelectedColumn.Length; k++)
{
stackss[k] = rd[k].ToString();
Response.Write("second rowsssss ==== " + stackss[k]);
if (k + 1 == splitSelectedColumn.Length)
{
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("compare flag checking");
Response.Write("Execute LABEL");
listBtnOrLbl.Add("label");
compareFlag = 0;
}
}
}
}
}
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
rd.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Gridview templatefield will generate when user click Refresh button. The above coding is that one to generate column and templatefield
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Response.Write("<br/>compare flag checking OVER button count=======================" + listBtnOrLbl.Count);
if (e.Row.RowType == DataControlRowType.DataRow)
{
int size = splitGroupByColumn.Length;
//Button[] lnkBtn = new Button[size];
Label[] lblData = new Label[size];
Response.Write("<br/>Inside button count=======================" + listBtnOrLbl.Count);
if ("button".Equals(listBtnOrLbl[j]))
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
//lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
e.Row.Cells[i].Controls.Add(lnkView);
}
j++;
}
else
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
lblData[i] = new Label();
lblData[i].ID = "lblView";
lblData[i].Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
Response.Write("<br/>PRINT label==" + lblData[i].Text);
e.Row.Cells[i].Controls.Add(lblData[i]);
//e.Row.Visible = false;
}
j++;
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Response.Redirect("exit.aspx"); //for testing purpose I gave like this, But this method is not calling i think when user clicks button
Response.Write("testing....");
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('TESTING:')", true);
}
Output before user clicks the Button
output1
After clicks the button(first button)
output2
I already did like this before,but that was small one not more complex code like this. that was working fine. Now What i did wrong here?.
Thanks
I think ViewDetails() method is not calling when user clicks the button

Dynamically created controls in Page_Load()

I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database.
I know that for having events fired for dynamically created controls, I have to create this controls in Page_Load() or in Page_Init().
My project has a Master Page, in which I have a 1 second timer which updates a clock. This timer event calls my admin.aspx Page_Load() function, so my method which creates dynamic controls it's called every 1 second - connection to database is made every one second, please look below to my code.
It's a good practice to do that? Can you please propose some ideas?
protected void Page_Load(object sender, EventArgs e)
{
_SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
panelContent.Style.Add("background-color", _SinopticBackgroundColor);
Control c = GetControlThatCausedPostBack(this);
if (c != null)
{
if (c.ID.Equals("btnManageCategory"))
hfPageManage.Value = "category";
else if (c.ID.Equals("btnManageDevices"))
hfPageManage.Value = "device";
}
if (hfPageManage.Value.Equals("category"))
{
cbTreeViewGroup.Visible = false;
UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
}
else if (hfPageManage.Value.Equals("device"))
{
cbTreeViewGroup.Visible = true;
}
else
{
cbTreeViewGroup.Visible = false;
}
if (!Page.IsPostBack)
{
LoadFunctions(); // loads some values from database into datatables
}
else
{
}
}
And here is the functions which creates controls
private void UpdateSinopticCategoryManager(TreeNode node = null)
{
if (node == null)
return;
DataTable categoriiDT = null;
using (var connection = new SqlConnection(Database.ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM categories WHERE CategoryID = #CategoryID";
command.Parameters.Add("CategoryID", node.Value);
SqlDataAdapter ad = new SqlDataAdapter(command);
DataSet ds = new DataSet("CATEGORYPROPERTIES");
connection.Open();
ad.Fill(ds);
// verificam sa avem date
if (ds.Tables.Count <= 0)
return;
if (ds.Tables[0].Rows.Count <= 0)
return;
categoriiDT = ds.Tables[0];
}
}
// generate table
Table table = new Table();
table.Style.Add("position", "relative");
table.Style.Add("top", "20px");
table.Style.Add("margin-left", "20px");
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth = 1;
// header
TableHeaderRow hr = new TableHeaderRow();
for (int i = 0; i < 2; i++)
{
TableHeaderCell hc = new TableHeaderCell();
if (i > 0)
{
hc.Text = "FUNCTION";
//hc.Width = 200;
}
else
{
hc.Width = 100;
}
hr.Cells.Add(hc);
}
table.Rows.Add(hr);
var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
where a.ColumnName.ToLowerInvariant().Contains("input")
select a.ColumnName).ToArray();
if (inputs.Count() <= 0)
return;
//rows input
for (int i = 0; i < inputs.Count(); i++)
{
TableRow tableRow = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
// adaugare 2 dropdownlist
DropDownList categList = new DropDownList();
categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
foreach (DataRow row in functionsCategories.Rows)
{
categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
}
DropDownList funcList = new DropDownList();
int selF = 0, selC = 0;
for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
{
funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
{
selF = fi;
selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
}
}
funcList.SelectedIndex = selF;
categList.SelectedIndex = functionsCategories.Rows.IndexOf(
(from c in functionsCategories.AsEnumerable()
where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
select c).FirstOrDefault());
cell.Controls.Add(categList);
cell.Controls.Add(funcList);
}
else
{
Label label = new Label();
label.Text = "INPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
tableRow.Cells.Add(cell);
}
table.Rows.Add(tableRow);
}
//rows output
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
DropDownList list = new DropDownList();
list.Width = 200;
list.Items.AddRange(GetOutputFunctions());
list.BorderColor = Color.Goldenrod;
cell.Controls.Add(list);
}
else
{
Label label = new Label();
label.Text = "OUTPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
// add table to panel
panelContent.Controls.Add(table);
}
It's about this: DropDownList categList = new DropDownList();
This may get answered more quickly and effectively in codereview https://codereview.stackexchange.com/

Why won't the label populate

I have been trying to create a chess strategy application. I seem to be having issues with trying to get the label1 control to populate during run time. I am actually pretty new to the idea of dynamically creating events like 'mouse enter, mouse leave' How do I get the label to show the coordinates in the mouse enter event
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Numbers.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) =>
{
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
Try this.. It was not populating because of a out of range.. iRow always = 8...
Add this class to your project.
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number); }
}
public ChessSquare()
{
}
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
Replace the FormLoad method with this:
int blockSize = 20;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65+i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.AliceBlue : Color.White;
Panel p = new Panel()
{ Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j+15),
};
p.MouseEnter+=new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
And add those two methods to your code:
void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel) sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
I there are several ways of doing it... This one is pretty straight forward.

table rendering problem in browser

I have below code of drawing a stage for seat availability. the problem is when page loads the default stage is drawn based on category color. but when i choose particular group from dropdown and it will show a stage from particular group seat availability.
problem is after i choose group it will take too much time... how can i draw stage with
minimum time my logic of creating stage is below.
-- My idea is to fill (red color only) LOGIC on dropdown selected index changed.
private void CreateDynamicTable()
{
string str = #"Data Source=SHREE\SQLEXPRESS;Initial Catalog=StageCraftNew;User ID=sa;Password=vivek";
SqlConnection con = new SqlConnection(str);
// FOR SEAT ASSIGNMENT (RED COLOR)
SqlCommand cmdSeat = new SqlCommand("Select FName,LName,SeatNo from Person_Master a,Member_Master b,SeatAssign_Master c where a.Personid=b.Personid and b.Memberid=c.memberid and b.Active='True' and c.Year='" + 2 + "' and GID='" + DropDownList1.SelectedIndex + "'", con);
SqlDataAdapter daSeat = new SqlDataAdapter(cmdSeat);
DataSet dsSeat = new DataSet();
daSeat.Fill(dsSeat);
// FOR SEAT ALPHABETS (BLUE COLOR)
SqlCommand cmdSeatMaster = new SqlCommand("select cm.CId,sm.Row,sm.ColorCode,cm.CategoryColor from Category_master cm,Seat_Master sm where cm.CId=sm.CId", con);
SqlDataAdapter daSeatMaster = new SqlDataAdapter(cmdSeatMaster);
DataSet dsSeatMaster = new DataSet();
daSeatMaster.Fill(dsSeatMaster);
// FOR STAGE DRAW
Table tbl = new Table();
using (SqlConnection conn = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("select * from Stage", conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
int tblRows = ds.Tables[0].Rows.Count;
int tblCols = ds.Tables[0].Columns.Count;
// Create a Table and set its properties
tbl.BorderStyle = BorderStyle.Solid;
tbl.CellSpacing = 0;
tbl.Attributes.Add("style","width:850px;height:auto;table-layout:fixed;margin-top:40px;font-size:13px;font-family:verdana");
// FOR STAGE DRAW
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
string alpha = "";
for (int j = 1; j < tblCols; j++)
{
TableCell tc = new TableCell();
tc.BackColor = System.Drawing.Color.White;
Label lbl = new Label();
if (ds.Tables[0].Rows[i][j].ToString() == "55" || ds.Tables[0].Rows[i][j].ToString() == "56")
{
lbl.Text = " ";
}
else
{
lbl.Text = ds.Tables[0].Rows[i][j].ToString();
}
if (alpha == "")
{
Regex r = new Regex("^[A-Z]*$");
if (r.IsMatch(lbl.Text))
{
alpha = lbl.Text;
}
}
// FOR SEAT ALPHABETS (BLUE COLOR)
for (int row = 0; row < dsSeatMaster.Tables[0].Rows.Count; row++)
{
for (int col = 0; col < dsSeatMaster.Tables[0].Columns.Count; col++)
{
if (dsSeatMaster.Tables[0].Rows[row]["Row"].ToString() == alpha)
{
tc.BackColor = System.Drawing.ColorTranslator.FromHtml(dsSeatMaster.Tables[0].Rows[row]["ColorCode"].ToString());
tc.Attributes.Add("style", "text-align:center");
}
}
}
// FOR CATEGORY COLOR
for (int row = 0; row < dsSeatMaster.Tables[0].Rows.Count; row++)
{
for (int col = 0; col < dsSeatMaster.Tables[0].Columns.Count; col++)
{
if (dsSeatMaster.Tables[0].Rows[row]["Row"].ToString() == alpha)
{
tc.BackColor = System.Drawing.ColorTranslator.FromHtml(dsSeatMaster.Tables[0].Rows[row]["CategoryColor"].ToString());
tc.Attributes.Add("style", "text-align:center");
}
}
}
// FOR SEAT ASSIGNMENT (RED COLOR)
for (int row = 0; row < dsSeat.Tables[0].Rows.Count; row++)
{
for (int col = 0; col < dsSeat.Tables[0].Columns.Count; col++)
{
Regex r = new Regex("^[A-Z]*$");
if (r.IsMatch(ds.Tables[0].Rows[i][j].ToString()) && ds.Tables[0].Rows[i][j].ToString() != "")
{
tc.BackColor = System.Drawing.ColorTranslator.FromHtml("#ADD8E6");
tc.Attributes.Add("style", "text-align:center");
}
else if (ds.Tables[0].Rows[i][j].ToString() == "")
{
tc.BackColor = System.Drawing.Color.White;
}
else if (alpha + "" + ds.Tables[0].Rows[i][j].ToString() == dsSeat.Tables[0].Rows[row]["SeatNo"].ToString() && alpha + "" + ds.Tables[0].Rows[i][j].ToString() != "")
{
tc.Attributes.Add("class", "demo-tip-twitter");
tc.Attributes.Add("style", "cursor:pointer;text-align:center;");
tc.ToolTip = "Seat: "+ alpha + "" + ds.Tables[0].Rows[i][j].ToString() + "\n" + dsSeat.Tables[0].Rows[row]["Fname"].ToString() + " " + dsSeat.Tables[0].Rows[row]["Lname"].ToString();
tc.BackColor = System.Drawing.Color.Red;
}
}
}
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
}
form1.Controls.Add(tbl);
}
}
}
Nothing stands out in your code, but I didn't notice that you have two loops that are almost identical to each other:
// FOR SEAT ALPHABETS (BLUE COLOR)
for (int row = 0; row < dsSeatMaster.Tables[0].Rows.Count; row++)
{
for (int col = 0; col < dsSeatMaster.Tables[0].Columns.Count; col++)
{
if (dsSeatMaster.Tables[0].Rows[row]["Row"].ToString() == alpha)
{
tc.BackColor = System.Drawing.ColorTranslator.FromHtml(dsSeatMaster.Tables[0].Rows[row]["ColorCode"].ToString());
tc.Attributes.Add("style", "text-align:center");
}
}
}
// FOR CATEGORY COLOR
for (int row = 0; row < dsSeatMaster.Tables[0].Rows.Count; row++)
{
for (int col = 0; col < dsSeatMaster.Tables[0].Columns.Count; col++)
{
if (dsSeatMaster.Tables[0].Rows[row]["Row"].ToString() == alpha)
{
tc.BackColor = System.Drawing.ColorTranslator.FromHtml(dsSeatMaster.Tables[0].Rows[row]["CategoryColor"].ToString());
tc.Attributes.Add("style", "text-align:center");
}
}
}
I'm not sure what the desired effect is, but it looks like you could remove one of the loops and fit the logic into one. I don't know what your measure of slow is, but that should help to speed things up a little.

Categories