table rendering problem in browser - c#

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.

Related

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/

Display Very Large Data in Horizontal Column DataGridView

I Want to Display this very large data into DataGridView.
But i don't know how to do that.
My Data in Sql Table
http://s13.postimg.org/5dodas0k7/data_di_tabel.png
I Want The Data is Displayed like this
http://s18.postimg.org/apnrbbxrd/tampilan_data_yg_diinginkan.png
I Can't display the data with SqlDataAdapter, so i use SqlDataReader in my cx Class.
Here's my code:
public partial class frmPartProduction : DevExpress.XtraEditors.XtraForm
{
public frmPartProduction()
{
InitializeComponent();
}
private void frmPartProduction_Load(object sender, EventArgs e)
{
txtTglAwal.EditValue = DateTime.Now;
txtTglAkhir.EditValue = DateTime.Now.AddMonths(1);
addRow();
}
private void addRow()
{
cx.Sql = "select PartNumber,PartName,BeginingStok from Part";
cx.Execr();
while (cx.Read())
{
String str = "";
for (int i = 0; i < 8; i++)
{
if (i == 0) str = "Forecast";
if (i == 1) str = "Stok Condition by Forecast";
if (i == 2) str = "Production";
if (i == 3) str = "Stok Condition by Production";
if (i == 4) str = "Safety Stok";
if (i == 5) str = "Schedjule Receipt";
if (i == 6) str = "Outgoing";
if (i == 7) str = "PO Release";
DG.Rows.Add();
int row = DG.RowCount - 1;
if (i == 0)
DG.Rows[row].Cells[0].Style.ForeColor = Color.Black;
else
DG.Rows[row].Cells[0].Style.ForeColor = Color.White;
DG.Rows[row].Cells[0].Value = cx.getString("PartNumber");
DG.Rows[row].Cells[1].Value = cx.getString("PartName");
DG.Rows[row].Cells[2].Value = str;
DG.Rows[row].Cells[3].Value = cx.getString("BeginingStok");
}
}
}
private void btnView_Click(object sender, EventArgs e)
{
while (DG.ColumnCount > 4)
{
DG.Columns.RemoveAt(4);
}
DateTime tgl_awal = Convert.ToDateTime(txtTglAwal.Text);
DateTime tgl_akhir = Convert.ToDateTime(txtTglAkhir.Text);
while (tgl_awal <= tgl_akhir)
{
if (tgl_awal.ToString("dddd") != "Saturday" && tgl_awal.ToString("dddd") != "Sunday")
{
DG.Columns.Add("", tgl_awal.ToString("dd-MMM-yyyy"));
DG.Columns[DG.ColumnCount - 1].Width = 80;
}
tgl_awal = tgl_awal.AddDays(1);
}
DateTime tgl;
for (int row = 0; row < DG.RowCount; row++)
{
String PartNumber = DG.Rows[row].Cells[0].Value.ToString();
String Description = DG.Rows[row].Cells[2].Value.ToString();
for (int col = 4; col < DG.ColumnCount; col++)
{
tgl = Convert.ToDateTime(DG.Columns[col].HeaderText);
if (Description == "Safety Stok")
{
cx.Sql = "select LimitStok from Part where PartNumber = #PartNumber";
cx.Param("#PartNumber", PartNumber);
cx.Param("#Description", Description);
cx.Param("#tgl", tgl);
cx.Execr();
if (cx.Read())
{
DG.Rows[row].Cells[col].Value = cx.getInt("LimitStok");
}
else
{
DG.Rows[row].Cells[col].Value = 0;
}
}
else
{
cx.Sql = "select qty from PartProduction where PartNumber = #PartNumber and tgl = #tgl and Description = #Description";
cx.Param("#PartNumber", PartNumber);
cx.Param("#Description", Description);
cx.Param("#tgl", tgl);
cx.Execr();
if (cx.Read())
{
DG.Rows[row].Cells[col].Value = cx.getFloat("qty");
}
else
{
DG.Rows[row].Cells[col].Value = 0;
}
}
}
}
}
}
I Initialized the DataGrid Column with addRow() method,
and i add date column in btnView_Click.
how can i display the date, in horizontal display?:-(example,
the table
PartNumber PartName Description Tgl Qty
100 Part X Forecast 01-10-2013 10
100 Part X Forecast 02-10-2013 10
100 Part X Forecast 03-10-2013 10
I Want the datagrid display is like this
DataGrid Display
PartNumber PartName 01-10-2013 02-10-2013 03-10-2013
100 Part X 0 0 2
101 Part Y 0 0 2
102 Part Z 2 0 2
You can use the Following code to bind the Data from database to GridView.
Please change the ConnectionString and SqlQuery asper your requirement.
private void getData()
{
String strCon = "Data Source=(local);Initial Catalog=database;uid=uid;pwd=pwd;Integrated Security=True;";
using (SqlConnection sqlCon = new SqlConnection(strCon))
{
String strCmd = "select PartNumber,PartName,BeginingStok from Part";
using (SqlCommand sqlcommand = new SqlCommand(strCmd, sqlCon))
{
sqlCon.Open();
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlcommand))
{
DataSet ds = new DataSet();
sqlAdapter.Fill(ds);
//DG.DataSource = ds.Tables[0];
foreach (DataRow newrow in ds.Tables[0].Rows)
{
String str = "";
for (int i = 0; i < 8; i++)
{
if (i == 0) str = "Forecast";
if (i == 1) str = "Stok Condition by Forecast";
if (i == 2) str = "Production";
if (i == 3) str = "Stok Condition by Production";
if (i == 4) str = "Safety Stok";
if (i == 5) str = "Schedjule Receipt";
if (i == 6) str = "Outgoing";
if (i == 7) str = "PO Release";
DG.Rows.Add();
int row = DG.RowCount - 1;
if (i == 0)
DG.Rows[row].Cells[0].Style.ForeColor = Color.Black;
else
DG.Rows[row].Cells[0].Style.ForeColor = Color.White;
DG.Rows[row].Cells[0].Value = newrow["PartNumber"];
DG.Rows[row].Cells[1].Value = newrow["PartName"];
DG.Rows[row].Cells[2].Value = str;
DG.Rows[row].Cells[3].Value = newrow["BeginingStok"];
}
}
}
}
}
}

Display pictures with their name from database in winforms?

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.

Add only a percentage of rows to DataTable

So i'm making a program to Audit some of our workers randomly. And i'm trying to make a program to scan our Access DB and pull a percentage of orders. But i want to randomly select the orders, i dont want just the top 5% or something.
static DataTable RandomSelect(double errPercentage,string User)
{
OleDbConnection conn = new OleDbConnection(strAccessConn);
string query = "SELECT ControlNumber FROM Log WHERE User ='" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
DataTable dtRandomRows = new DataTable();
try
{
adapter.Fill(dt);
//dtRandomRows = dt.Clone();
Random rDom = new Random();
int i = 0;
for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
{
i = rDom.Next(1, dt.Rows.Count);
//dtRandomRows.Rows.Add(dt.Rows[i]);
dtRandomRows.ImportRow(dt.Rows[i]);
}
dtRandomRows.AcceptChanges();
}
catch (OleDbException ex)
{
}
return dtRandomRows;
}
The code above works, but it randomly selects rows from the entire table of the ControlNumbers (orders) and puts them all into dtRandomRows. However, i just want this to select the 'errPercentage' or rows randomly...any thoughts?
Random rand = new Random();
// Mark every row as not selected yet.
int[] nonSelectedRows = new int[dt.Rows.Count];
for(int i = 0; i < dt.Rows.Count; i++)
nonSelectedRows[i] = 1;
int numSelected = 0;
int numLeft = dt.Rows.Count;
int targetNum = dt.Rows.Count * errPercentage;
while(numSelected < targetNum)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
// Each record has a 1/numleft chance of getting selected.
boolean isSelected = rand.Next(numLeft) == 0;
// Check to make sure it hasn't already been selected.
if(isSelected && nonSelectedRows[row] > 0)
{
dtRandomRows.ImportRow(dt.Rows[row]);
nonSelectedRows[row] = -1; // Mark this row as selected.
numSelected++;
numLeft--;
}
// We've already found enough to match our targetNum.
if(numSelected >= targetNum)
break;
}
}

Categories