How do I auto generate content based on my database? - asp.net

Good day. I have this content form but I do not know how to generate it automatically depending on the number of results from the database. I'm fairly new to ASP.Net
<asp:Content ID="Content1" ContentPlaceHolderID="AdminMain" runat="server">
<h1 class="container"><asp:Label runat="server" ID="PageTitle"></asp:Label></h1>
<div class="container">
<hgroup class="title">
<h1 class="post-title">
<asp:Label runat="server" ID="PostName"></asp:Label>
</h1>
<h6>Posted by <asp:Label runat="server" ID="AuthorName"></asp:Label> on <asp:Label runat="server" ID="PublushedDate"></asp:Label></h6>
</hgroup>
<div class="post-content">
<asp:Label runat="server" ID="PostContent"></asp:Label>
</div>
<div class="post-tags">
<h6>Categorized as:<asp:Label runat="server" ID="PostCategory"></asp:Label><br /></h6>
<h6>Tagged as:<asp:Label runat="server" ID="PostTag"></asp:Label></h6>
</div>
Here's what I'm going to populate it with:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GetAllPosts();
}
}
private void GetAllPosts()
{
var sql = "SELECT p.*, t.Id as TagId, t.Name as TagName, " +
"t.UrlFriendlyName as TagUrlFriendlyName, u.Username FROM Posts p " +
"LEFT JOIN PostsTagsMap m ON p.Id = m.PostId " +
"LEFT JOIN Tags t ON t.Id = m.TagId " +
"INNER JOIN Users u ON u.Id = p.AuthorId";
SqlConnection SQLConn = new SqlConnection(con);
SqlCommand SQLComm = new SqlCommand(sql,SQLConn);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
foreach (DataRow row in dt.Rows)
{
PageTitle.Text = "All Posts";
PostName.Text = row["Title"].ToString();
AuthorName.Text = row["Username"].ToString();
PublishedDate.Text = Convert.ToDateTime(row["DatePublished"]).ToString();
PostContent.Text = row["Content"].ToString();
PostCategory.Text = "Events";
PostTag.Text = row["TagName"].ToString();
}
}
I appreciate the input and the help.

Webforms are terrible.
int i = 1;
PageTitle.Text = "All Posts";
foreach (DataRow row in dt.Rows)
{
Label newlabel = new Label();
PlaceHolder newplaceholder = new PlaceHolder();
newlabel.ID ="PostName" + i.ToString() + "</a>";
//html.Append(#"<hgroup class=""title"">");
//html.Append(#"<h1 class=""post-title"">");
PanelPosts.Controls.Add(newlabel);
newlabel.Text = #"<hgroup class=""title""><h1 class=""post-title"">" + row["Title"].ToString() + "</h1>";
newlabel = new Label();
newlabel.ID = "AuthorName" + i.ToString();
html.Append(#"<h6>");
PanelPosts.Controls.Add(newlabel);
newlabel.Text ="Posted by: "+row["Username"].ToString()+" on ";
newlabel = new Label();
newlabel.ID = "PublishedDate" + i.ToString();
PanelPosts.Controls.Add(newlabel);
newlabel.Text = row["DatePublished"].ToString()+"</h6>";
html.Append("</hgroup>");
newlabel = new Label();
newlabel.ID = "PostContent" + i.ToString();
PanelPosts.Controls.Add(newlabel);
newlabel.Text = #"<div class=""post-content""><h3>" + row["Content"].ToString() + "</h3><br /></div>";
newlabel = new Label();
newlabel.ID = "PostCategory" + i.ToString();
PanelPosts.Controls.Add(newlabel);
newlabel.Text = #"<div class=""post-tags""><h6>Categorized as: " + "Category" + " <br/> </h6>";
newlabel = new Label();
newlabel.ID = "PostTag" + i.ToString();
PanelPosts.Controls.Add(newlabel);
newlabel.Text = #"<h6>Tagged as: <a href=""/archive/tag/{TagUrlFriendlyName}/"">"+row["TagName"].ToString()+"</div>";
PanelPosts.Controls.Add(new LiteralControl("<br />"));
i++;
}

Related

User should only be able to select 1 item in a list only once

I have a gridview where I'm allowing user to select items for billing. now my problem is that the user is able to select same item twice in only one bill.
screen for reference:
Here the user is able to select duplicate items in the list which is not good.
my ASPX Markup:
<asp:GridView ID="Gridview1" runat="server" CssClass="table table-bordered table-hover table-responsive" ShowFooter="True" AutoGenerateColumns="False" OnRowDataBound="gvRowDataBound" OnRowDeleting="Gridview1_RowDeleting1" EmptyDataText="Data Not Available">
<Columns>
<asp:CommandField ShowDeleteButton="true" ControlStyle-CssClass="btn btn-danger fa fa-trash" DeleteText="" HeaderText="Remove Items" />
<asp:BoundField DataField="RowNumber" HeaderText="Sl. No." />
<asp:TemplateField HeaderText="Item Name" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:DropDownList ID="drpItemname" runat="server" Width="200px" CssClass="form-control select2" OnSelectedIndexChanged="GetItemDetails" AutoPostBack="true"></asp:DropDownList>
</ItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="HSN Code" Visible="false" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txthsn" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Available Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQttyAvailable" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQtty" runat="server" CssClass="form-control" OnTextChanged="CalculateTotal" AutoPostBack="true" Enabled="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtUnitPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtdisc" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtsgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtcgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="I.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtigst" runat="server" AutoPostBack="true" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price" ConvertEmptyStringToNull="False" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtTotalPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="AddItem" CausesValidation="False" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My c# code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Mylogic();
SetInitialRow();
ce1.StartDate = DateTime.Now.AddDays(-60);
ce1.SelectedDate = DateTime.Now.Date;
BindGrid();
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dt.Columns.Add(new DataColumn("Column7", typeof(string)));
dt.Columns.Add(new DataColumn("Column8", typeof(string)));
dt.Columns.Add(new DataColumn("Column9", typeof(string)));
dt.Columns.Add(new DataColumn("Column10", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dr["Column7"] = string.Empty;
dr["Column8"] = string.Empty;
dr["Column9"] = string.Empty;
dr["Column10"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox QttyAvailable = row.FindControl("txtQttyAvailable") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox HsnCode = row.FindControl("txthsn") as TextBox;
TextBox Discount = row.FindControl("txtdisc") as TextBox;
TextBox SGST = row.FindControl("txtsgst") as TextBox;
TextBox CGST = row.FindControl("txtcgst") as TextBox;
TextBox IGST = row.FindControl("txtigst") as TextBox;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
string str = "select * from Stock where itemname='" + ddl1.SelectedItem.ToString() + "'";
SqlCommand com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
UnitPrice.Text = reader["unitprice"].ToString();
QttyAvailable.Text = reader["qtty"].ToString();
HsnCode.Text = reader["hsn"].ToString();
Discount.Text = reader["disc"].ToString();
SGST.Text = reader["sgst"].ToString();
CGST.Text = reader["cgst"].ToString();
IGST.Text = reader["igst"].ToString();
}
reader.Close();
conn.Close();
}
}
}
}
protected void CalculateTotal(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
foreach (GridViewRow row in Gridview1.Rows)
{
TextBox lblQty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox lblReceiveQty = row.FindControl("txtQtty") as TextBox;
if (lblQty != null && lblReceiveQty != null)
{
int Qty = 0, ReceiveQty = 0;
if (!string.IsNullOrEmpty(lblQty.Text))
{
Qty = int.Parse(lblQty.Text);
}
if (!string.IsNullOrEmpty(lblReceiveQty.Text))
{
ReceiveQty = int.Parse(lblReceiveQty.Text);
}
if (ReceiveQty > Qty)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Required quantity can not ne greater than available stock!', 'Royal Riders, Vijayapura', 'warning');", true);
lblReceiveQty.Text = "";
lblReceiveQty.Focus();
}
else if (Qty >= ReceiveQty)
{
TextBox AQtty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox QttyReq = row.FindControl("txtQtty") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox TotPrice = row.FindControl("txtTotalPrice") as TextBox;
TextBox DiscountPrice = row.FindControl("txtdisc") as TextBox;
DropDownList ItemName = row.FindControl("drpItemname") as DropDownList;
Control ctrl = row.FindControl("txtQtty") as TextBox;
if (ctrl != null)
{
TextBox txt1 = (TextBox)ctrl;
if (txt.ClientID == txt1.ClientID)
{
decimal totamt = Convert.ToDecimal(QttyReq.Text) * Convert.ToDecimal(UnitPrice.Text);
decimal discountrate = (totamt) - (totamt * Convert.ToDecimal(DiscountPrice.Text)) / 100;
TotPrice.Text = discountrate.ToString("#,0.00");
}
}
}
}
}
}
public static decimal totalgst;
public static decimal totalnetamt;
public static Int32 InitialStock;
protected void gvRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpItemName = (e.Row.FindControl("drpItemName") as DropDownList);
foreach (GridViewRow row2 in Gridview1.Rows)
{
TextBox txt = row2.FindControl("txtTotalPrice") as TextBox;
txt.Text = "0";
}
drpItemName.DataSource = GetData("SELECT itemname FROM Stock where rem != '1'");
drpItemName.DataTextField = "itemname";
drpItemName.DataValueField = "itemname";
drpItemName.DataBind();
drpItemName.Items.Insert(0, new ListItem("Please select"));
}
}
private DataSet GetData(string query)
{
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box6.Text;
dtCurrentTable.Rows[i - 1]["Column7"] = box7.Text;
dtCurrentTable.Rows[i - 1]["Column8"] = box8.Text;
dtCurrentTable.Rows[i - 1]["Column9"] = box9.Text;
dtCurrentTable.Rows[i - 1]["Column10"] = box10.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
box5.Text = dt.Rows[i]["Column5"].ToString();
box6.Text = dt.Rows[i]["Column6"].ToString();
box7.Text = dt.Rows[i]["Column7"].ToString();
box8.Text = dt.Rows[i]["Column8"].ToString();
box9.Text = dt.Rows[i]["Column9"].ToString();
box10.Text = dt.Rows[i]["Column10"].ToString();
rowIndex++;
if (!string.IsNullOrEmpty(box10.Text) && !string.IsNullOrEmpty(box10.Text))
{
box10.Text = dt.Rows[i]["Column10"].ToString();
}
else
{
box10.Text = "0";
}
}
}
}
}
protected void Confirm(object sender, EventArgs e)
{
decimal sum = 0;
decimal grandgst = 0;
try
{
foreach (GridViewRow g12 in Gridview1.Rows)
{
Control ctrl2 = g12.FindControl("txtigst") as TextBox;
if (ctrl2 != null)
{
TextBox txt1 = (TextBox)ctrl2;
TextBox cgst = g12.FindControl("txtcgst") as TextBox;
TextBox sgst = g12.FindControl("txtsgst") as TextBox;
TextBox igst = g12.FindControl("txtigst") as TextBox;
TextBox linegst = g12.FindControl("txtTotalPrice") as TextBox;
TextBox totamt = g12.FindControl("txtTotalPrice") as TextBox;
sum += decimal.Parse(((TextBox)(g12.Cells[10].FindControl("txtTotalPrice"))).Text);
decimal fcgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(cgst.Text) / 100;
decimal fsgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(sgst.Text) / 100;
decimal figst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(igst.Text) / 100;
decimal ftot = Convert.ToDecimal(totamt.Text);
totalgst = fcgst + fsgst + figst;
grandgst += totalgst;
totalnetamt = grandgst + sum;
}
}
lblGstTotal.Text = grandgst.ToString();
lblGTotal.Text = sum.ToString();
lblGrandTotal.Text = (sum + grandgst).ToString();
foreach (GridViewRow g1 in Gridview1.Rows)
{
string ITEMNAME = (g1.FindControl("drpItemname") as DropDownList).Text;
string HSN = (g1.FindControl("txthsn") as TextBox).Text;
string QTY = (g1.FindControl("txtQtty") as TextBox).Text;
string UP = (g1.FindControl("txtUnitPrice") as TextBox).Text;
string DIS = (g1.FindControl("txtdisc") as TextBox).Text;
string SGST = (g1.FindControl("txtsgst") as TextBox).Text;
string CGST = (g1.FindControl("txtcgst") as TextBox).Text;
string IGST = (g1.FindControl("txtigst") as TextBox).Text;
string TOT = (g1.FindControl("txtTotalPrice") as TextBox).Text;
string InsertQuery = "Insert into Sales(bno,cdate,ctime,name,mobileno,address,gstno,pan,description,hsn,qtty,rate,disc,sgst,cgst,igst,linetotal,netamt,totalgst,grsamt,status,rem) values(#bno,#cdate,#ctime, #name, #mobileno, #address, #gstno, #pan, #description, #hsn, #qtty, #rate, #disc, #sgst, #cgst,#igst,#linetotal,#netamt,#totalgst,#grsamt,'1','0')";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(InsertQuery, con))
{
cmd.Parameters.AddWithValue("#bno", Convert.ToInt64(lblBillNo.Text));
cmd.Parameters.AddWithValue("#cdate", txtBDate.Text.ToString());
cmd.Parameters.AddWithValue("#ctime", systemtime.ToString());
cmd.Parameters.AddWithValue("#name", txtcname.Text);
cmd.Parameters.AddWithValue("#mobileno", txtcmobile.Text);
cmd.Parameters.AddWithValue("#address", txtcaddress.Text);
cmd.Parameters.AddWithValue("#gstno", txtgst.Text);
cmd.Parameters.AddWithValue("#pan", txtcpan.Text);
cmd.Parameters.AddWithValue("#description", ITEMNAME);
cmd.Parameters.AddWithValue("#hsn", HSN);
cmd.Parameters.AddWithValue("#qtty", QTY);
cmd.Parameters.AddWithValue("#rate", Convert.ToDecimal(UP));
cmd.Parameters.AddWithValue("#disc", Convert.ToDecimal(DIS));
cmd.Parameters.AddWithValue("#sgst", Convert.ToDecimal(SGST));
cmd.Parameters.AddWithValue("#cgst", Convert.ToDecimal(CGST));
cmd.Parameters.AddWithValue("#igst", Convert.ToDecimal(IGST));
cmd.Parameters.AddWithValue("#linetotal", Convert.ToDecimal(TOT));
cmd.Parameters.AddWithValue("#grsamt", (lblGTotal.Text));
cmd.Parameters.AddWithValue("#totalgst", Convert.ToDecimal(lblGstTotal.Text));
cmd.Parameters.AddWithValue("#netamt", Convert.ToDecimal(lblGrandTotal.Text));
int i = cmd.ExecuteNonQuery();
if(i > 0)
{
DropDownList ItemName = g1.FindControl("drpItemname") as DropDownList;
TextBox ReqQtty = g1.FindControl("txtQtty") as TextBox;
using (SqlConnection DeductStockCon = new SqlConnection(constring))
{
string query = "update Stock set qtty=CAST(IsNULL(qtty, '0') as int) - '" + Convert.ToInt32(ReqQtty.Text) + "' where itemname='" + ItemName.SelectedItem.ToString() + "'";
DeductStockCon.Open();
using (SqlCommand DeductStockCmd = new SqlCommand(query, DeductStockCon))
{
int j = DeductStockCmd.ExecuteNonQuery();
if (j > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Items inserted successfully!', 'Royal Riders, Vijayapura', 'success');", true);
}
}
}
}
}
}
}
LoadReceipt();
Clear();
Mylogic();
SetInitialRow();
}
catch (Exception ex)
{
throw ex;
}
}
private void Clear()
{
txtcname.Text = "";
txtcmobile.Text = "";
txtcaddress.Text = "";
txtcpan.Text = "";
txtgst.Text = "";
drpMode.SelectedValue = "--Select Payment Mode--";
}
private void Mylogic()
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT MAX(bno) + 1 as Billno FROM Sales", con))
lblBillNo.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
}
protected void AddItem(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
decimal sum = 0;
foreach (GridViewRow row1 in Gridview1.Rows)
{
TextBox val1 = row1.FindControl("txtTotalPrice") as TextBox;
if (!string.IsNullOrEmpty(val1.Text) && !string.IsNullOrEmpty(val1.Text))
{
sum += 0;
}
else
{
sum += decimal.Parse(((TextBox)(row1.Cells[10].FindControl("txtTotalPrice"))).Text);
}
}
lblGTotal.Text = sum.ToString();
}
catch (Exception ex)
{
lblGTotal.Text = ex.Message.ToString();
}
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
SetInitialRow();
BindGrid();
}
protected void BindGrid()
{
Gridview1.DataSource = ViewState["CurrentTable"] as DataTable;
Gridview1.DataBind();
}
private void LoadReceipt()
{
SqlConnection CN;
string MyConnectionString = null;
MyConnectionString = constring;
CN = new SqlConnection(MyConnectionString);
CN.Open();
string SQL = null;
SQL = "SELECT * FROM Sales where bno=(select max(bno) as 'Billno' from Sales)";
SqlDataAdapter myDA = new SqlDataAdapter(SQL, CN);
CN.Close();
SalesDataset DS = new SalesDataset();
myDA.Fill(DS, "Sales");
ReportDocument myRPT = new ReportDocument();
myRPT.Load(Server.MapPath("Reports/BillReciept.rpt"));
myRPT.SetDataSource(DS);
rptSales.ReportSource = myRPT;
rptSales.SeparatePages = false;
}
protected void btnLastReport_Click(object sender, EventArgs e)
{
LoadReceipt();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
protected void Gridview1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
dt.Rows.RemoveAt(e.RowIndex);
Gridview1.DataSource = dt;
Gridview1.DataBind();
SetPreviousData();
if(Gridview1.Rows.Count <= 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('This is the only item in the list!', 'Royal Riders, Vijayapura', 'success');", true);
SetInitialRow();
}
}
You can do it in two ways
Handle the code in GetItemDetails() Event Method do a foreach and check if the name selected in the drpItemname dropdown eqauls with the name of any of the previous drpItemname dropdownlist of the gridview
In the Method AddNewRowToGrid() before binding data to drpItemname dropdown remove those values from the list which are already selected in the previous drpItemname dropdown and then bind it and add row [Note this will work ambiguos because if user changes the dropdownvalue of previous list then you will get problem ]
Are these ideas helpfull ?
Ex 1 -
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if((ddl1.ClientId != ddl.ClientId) && (ddl1.SelectedIndex == ddl.SelectedIndex)){
return Response.Write("Error") //
}
}
}
}

Nested foreach() messing up

Good Day, guys.
I'm currentl making a full page overlay for navigation and I've been trying to figure out this problem for the past 2 days regarding my nested foreach() loops.
I have these pages which may be linked with posts. and here is what I'm trying to achieve:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
About Us Page
But what I'm getting is:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
Post 1/ Post 2/ Post3
About Us Page
Post 1/ Post 2/ Post3
Here are my code:
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"LEFT JOIN PagesPostsMap m ON po.Id = m.PostId " +
"LEFT JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
object value = row2["PostId"];
if (value != DBNull.Value)
{
if (row["Id"] != row2["PageId"])
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}
}
}
I'm sorry if the the classes and stuff are not adding up. I'm still trying to figure out how css and JS works.
And thank for helping me.
Your code is actually just doing what you tell it to do. For every row in your GetMain, you order everything in your dt2 (datatable2). If you want what you try to achive, you have to set a condition and put your second foreach into that condition.
if(tech parts row)
{
"your second foreach"
}
If I missunderstand anything, feel free to add more info
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"JOIN PagesPostsMap m ON po.Id = m.PostId " +
"JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}

aligning left and right in same line dynamically asp.net

I am Displaying Picture dynamically in gallery ,below picture i displayed product name,product weight , product color, product quality,origin and quantity.It is currently displayed in 6 lines,each item per line...
I want to display two items in each line and 6 item in 3 lines.First item should align left , second item on right on first line and so on.how can i do it? this is my code.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class jewellery : System.Web.UI.Page
{
public void select_data()
{
//String con_str = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\asim\bootstrap1 (1)\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
String con_str = #"Data Source=KHAN-PC\SQLEXPRESS;Initial Catalog=D:\ASIM\BOOTSTRAP1 (1)\APP_DATA\DATABASE.MDF;Integrated Security=True";
//string con_str = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\project\App_Data\Database.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(con_str);
con.Open();
string query = "select * from jewellery1";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
int n = 1;
String id = "Image";
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl section = new System.Web.UI.HtmlControls.HtmlGenericControl("section");
section.ID = "portfolio";
section.Attributes["class"] = "bg-light-gray";
System.Web.UI.HtmlControls.HtmlGenericControl row = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
row.Attributes["class"] = "row";
Byte[] bytes = (Byte[])reader["item_image"];
String item_name = (String)reader["item_name"];
String color = (String)reader["item_color"];
String weight = (String)reader["item_weight"];
String quality = (String)reader["item_quality"];
String clarity = (String)reader["item_clarity"];
String origin = (String)reader["item_origin"];
System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
createDiv.ID = "createDiv" + n + 11;
System.Web.UI.HtmlControls.HtmlGenericControl createDiv1 =
new System.Web.UI.HtmlControls.HtmlGenericControl("div");
System.Web.UI.HtmlControls.HtmlGenericControl hover = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hover.Attributes["class"] = "portfolio-hover";
System.Web.UI.HtmlControls.HtmlGenericControl hover_content = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hover_content.Attributes["class"] = "portfolio-hover-content";
System.Web.UI.HtmlControls.HtmlGenericControl i = new System.Web.UI.HtmlControls.HtmlGenericControl("i");
i.Attributes["class"] = "fa fa-2x";
createDiv1.ID = "createDiv" + n + 12;
createDiv1.Attributes["class"] = "col-md-4 col-sm-6 portfolio-item zoomIn animated";
createDiv1.Attributes["data-wow-duration"] = "1500ms";
createDiv1.Attributes["data-wow-delay"] = "100ms";
createDiv.Attributes["class"] = "portfolio-caption";
LinkButton a = new LinkButton();
a.Attributes["class"] = "portfolio-link";
a.Attributes["data-toggle"] = "modal";
a.Click += new EventHandler(test);
a.CommandArgument = item_name;
/* System.Web.UI.HtmlControls.HtmlGenericControl a = new System.Web.UI.HtmlControls.HtmlGenericControl("a");
a.Attributes["class"] = "portfolio-link";
a.Attributes["data-toggle"] = "modal";*/
System.Web.UI.HtmlControls.HtmlGenericControl h1 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h2 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h3 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h4 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h5 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h6 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
h1.Attributes["align"] = "LEFT";
h1.Attributes["style"] = "color:black";
h1.InnerHtml = "Name &nbsp &nbsp :&nbsp &nbsp " + item_name;
h2.Attributes["align"] = "RIGHT";
h2.Attributes["style"] = "color:black";
h2.InnerHtml = "color &nbsp &nbsp &nbsp &nbsp :&nbsp &nbsp " + color;
h3.Attributes["align"] = "LEFT";
h3.Attributes["style"] = "color:black";
h3.InnerHtml = "Weight &nbsp &nbsp: &nbsp &nbsp " + weight;
h4.Attributes["align"] = "LEFT";
h4.Attributes["style"] = "color:black";
h4.InnerHtml = "Quality &nbsp&nbsp: &nbsp " + quality;
h5.Attributes["align"] = "LEFT";
h5.Attributes["style"] = "color:black";
h5.InnerHtml = "Clarity &nbsp&nbsp: &nbsp " + clarity;
h6.Attributes["align"] = "LEFT";
h6.Attributes["style"] = "color:black";
h6.InnerHtml = "Origin &nbsp&nbsp: &nbsp " + origin;
System.Web.UI.HtmlControls.HtmlGenericControl hyp = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hyp.Attributes["class"] = "portfolio-link";
System.Web.UI.WebControls.Image tb = new System.Web.UI.WebControls.Image() { ID = "Image" + n + 10 };
tb.Height = 250;
tb.Width = 500;
tb.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
hover_content.Controls.Add(i);
a.Controls.Add(hover);
a.Controls.Add(hover_content);
a.Controls.Add(tb);
createDiv.Controls.Add(h1);
createDiv.Controls.Add(h2);
createDiv.Controls.Add(h3);
createDiv.Controls.Add(h4);
createDiv.Controls.Add(h5);
createDiv.Controls.Add(h6);
createDiv1.Controls.Add(a);
createDiv1.Controls.Add(createDiv);
// row.Controls.Add(createDiv1);
//section.Controls.Add(row);
divid1.Controls.Add(createDiv1);
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
n++;
}
}
protected void test(object sender, EventArgs e)
{
String wagerId = ((LinkButton)sender).CommandArgument;
Response.Redirect("awesome.aspx?eid=" + wagerId);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
select_data();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
Updated Code
Bro your code didn't work. I tried this way,its working somehow fine . It displays H1 on left ,H2 on right.thats fine but it also displays h3 in center,as it should be on next line.how can I resolve it.
h1.Attributes["class"] = "links left";
h1.Attributes["style"] = "color:black";
h1.InnerHtml = "Name &nbsp &nbsp :&nbsp &nbsp " + item_name;
h2.Attributes["class"] = "links right";
h2.Attributes["style"] = "color:black";
h2.InnerHtml = "color &nbsp &nbsp &nbsp &nbsp :&nbsp &nbsp " + color;
h3.Attributes["class"] = "links right";
h3.Attributes["style"] = "color:black";
h3.InnerHtml = "Weight &nbsp &nbsp: &nbsp &nbsp " + weight;
h4.Attributes["align"] = "LEFT";
h4.Attributes["style"] = "color:black";
h4.InnerHtml = "Quality &nbsp&nbsp: &nbsp " + quality;
<style>
.mainlinks
{
text-align:right;
margin-top:3px;
margin-right:10px;
margin-bottom:0px;
padding:0px;
}
a.links:link {
color: #FF0000; text-decoration: none;
text-align:left;
margin-left:8px;
margin-top:300px;
margin-bottom:0px;
padding:2px;
font-family:Arial, Helvetica, sans-serif;
font-size: 14px;
}
.right { float: right }
.left { float: left }
</style>
Use the following code. I've removed Attributes["align"] = "LEFT" part and added float: left;width: 50%;. Adjust the width percentage according to your needs.
h1.Attributes["style"] = "color:black;float: left;width: 50%; ";
h1.InnerHtml = "Name &nbsp &nbsp :&nbsp &nbsp " + item_name;
h2.Attributes["style"] = "color:black;float: left;width: 50%; ";
h2.InnerHtml = "color &nbsp &nbsp &nbsp &nbsp :&nbsp &nbsp " + color;
h3.Attributes["style"] = "color:black;float: left;width: 50%; ";
h3.InnerHtml = "Weight &nbsp &nbsp: &nbsp &nbsp " + weight;
h4.Attributes["style"] = "color:black;float: left;width: 50%; ";
h4.InnerHtml = "Quality &nbsp&nbsp: &nbsp " + quality;
h5.Attributes["style"] = "color:black;float: left;width: 50%; ";
h5.InnerHtml = "Clarity &nbsp&nbsp: &nbsp " + clarity;
h6.Attributes["style"] = "color:black;float: left;width: 50%; ";
h6.InnerHtml = "Origin &nbsp&nbsp: &nbsp " + origin;
UPDATE (Commented out the variables for adjusting in my VS)
var n = 1;
while(n < 5) {
System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
createDiv.ID = "createDiv" + n + 11;
System.Web.UI.HtmlControls.HtmlGenericControl createDiv1 =
new System.Web.UI.HtmlControls.HtmlGenericControl("div");
System.Web.UI.HtmlControls.HtmlGenericControl hover = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hover.Attributes["class"] = "portfolio-hover";
System.Web.UI.HtmlControls.HtmlGenericControl hover_content = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hover_content.Attributes["class"] = "portfolio-hover-content";
System.Web.UI.HtmlControls.HtmlGenericControl i = new System.Web.UI.HtmlControls.HtmlGenericControl("i");
i.Attributes["class"] = "fa fa-2x";
createDiv1.ID = "createDiv" + n + 12;
createDiv1.Attributes["class"] = "col-md-4 col-sm-6 portfolio-item zoomIn animated";
createDiv1.Attributes["data-wow-duration"] = "1500ms";
createDiv1.Attributes["data-wow-delay"] = "100ms";
createDiv.Attributes["class"] = "portfolio-caption";
LinkButton a = new LinkButton();
a.Attributes["class"] = "portfolio-link";
a.Attributes["data-toggle"] = "modal";
//a.Click += new EventHandler(test);
//a.CommandArgument = item_name;
/* System.Web.UI.HtmlControls.HtmlGenericControl a = new System.Web.UI.HtmlControls.HtmlGenericControl("a");
a.Attributes["class"] = "portfolio-link";
a.Attributes["data-toggle"] = "modal";*/
System.Web.UI.HtmlControls.HtmlGenericControl h1 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h2 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h3 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h4 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h5 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
System.Web.UI.HtmlControls.HtmlGenericControl h6 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
h1.Attributes["style"] = "color:black;float: left;width: 50%; ";
h1.InnerHtml = "Name &nbsp &nbsp :&nbsp &nbsp " + "item_name";
h2.Attributes["style"] = "color:black;float: left;width: 50%; ";
h2.InnerHtml = "color &nbsp &nbsp &nbsp &nbsp :&nbsp &nbsp " + "color";
h3.Attributes["style"] = "color:black;float: left;width: 50%; ";
h3.InnerHtml = "Weight &nbsp &nbsp: &nbsp &nbsp " + "weight";
h4.Attributes["style"] = "color:black;float: left;width: 50%; ";
h4.InnerHtml = "Quality &nbsp&nbsp: &nbsp " + "quality";
h5.Attributes["style"] = "color:black;float: left;width: 50%; ";
h5.InnerHtml = "Clarity &nbsp&nbsp: &nbsp " + "clarity";
h6.Attributes["style"] = "color:black;float: left;width: 50%; ";
h6.InnerHtml = "Origin &nbsp&nbsp: &nbsp " + "origin";
System.Web.UI.HtmlControls.HtmlGenericControl hyp = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
hyp.Attributes["class"] = "portfolio-link";
System.Web.UI.WebControls.Image tb = new System.Web.UI.WebControls.Image() { ID = "Image" + n + 10 };
tb.Height = 250;
tb.Width = 500;
tb.ImageUrl = "data:image/png;base64," /*+ Convert.ToBase64String(bytes)*/;
hover_content.Controls.Add(i);
a.Controls.Add(hover);
a.Controls.Add(hover_content);
a.Controls.Add(tb);
createDiv.Controls.Add(h1);
createDiv.Controls.Add(h2);
createDiv.Controls.Add(h3);
createDiv.Controls.Add(h4);
createDiv.Controls.Add(h5);
createDiv.Controls.Add(h6);
createDiv1.Controls.Add(a);
createDiv1.Controls.Add(createDiv);
// row.Controls.Add(createDiv1);
//section.Controls.Add(row);
divid1.Controls.Add(createDiv1);
n++;
}

Label does not show up in asp.net

I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.

Why can't I see my dynamically created controls?

When I click on the button just nothing happens!
public void cmdButton1_OnClick(object sender, EventArgs e)
{
Panel myPanel = new Panel();
myPanel.ID = "Panel1";
for (int i = 0; i < numtourist; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblNameL" + i.ToString();
myLabel.Text = "Трите имена на латиница ";
TextBox myTextBox1 = new TextBox();
myTextBox1.ID = "txtNameL" + i.ToString();
myPanel.Controls.Add(myLabel);
myPanel.Controls.Add(myTextBox1);
Label mylabel2 = new Label();
mylabel2.ID = "lblNameK" + i.ToString();
mylabel2.Text = "Трите имена на кирилица";
TextBox myTextBox2 = new TextBox();
myTextBox2.ID = "txtNameK" + i.ToString();
myPanel.Controls.Add(mylabel2);
myPanel.Controls.Add(myTextBox2);
Label myLabel3 = new Label();
myLabel3.ID = "lblEGN" + i.ToString();
myLabel3.Text = "EГН";
TextBox myTextBox3 = new TextBox();
myTextBox3.ID = "txtEGN" + i.ToString();
myPanel.Controls.Add(myLabel3);
myPanel.Controls.Add(myTextBox3);
Label myLabel4 = new Label();
myLabel4.ID = "lblPersonalCardNum" + i.ToString();
myLabel4.Text = "Номер на лична карта";
TextBox myTextBox4 = new TextBox();
myTextBox4.ID = "txtPersonalCardNum" + i.ToString();
myPanel.Controls.Add(myLabel4);
myPanel.Controls.Add(myTextBox4);
Label myLabel5 = new Label();
myLabel5.ID = "lblDateOfIssuePC " + i.ToString();
myLabel5.Text = "Дата на издаане на лична карта:";
TextBox myTextBox5 = new TextBox();
myTextBox5.ID = "txtDateOfIssuePC" + i.ToString();
myPanel.Controls.Add(myLabel5);
myPanel.Controls.Add(myTextBox5);
Label myLabel6 = new Label();
myLabel6.ID = "lblDateOfExpiryPC " + i.ToString();
myLabel6.Text = "Дата на валидност на лична карта:";
TextBox myTextBox6 = new TextBox();
myTextBox6.ID = "txtDateOfExpiryPC" + i.ToString();
myPanel.Controls.Add(myLabel6);
myPanel.Controls.Add(myTextBox6);
Label mylabel6_1 = new Label();
mylabel6_1.ID = "lblIssuedFrom" + i.ToString();
mylabel6_1.Text = "Издадеа от";
TextBox myTextBox6_1 = new TextBox();
myTextBox6_1.ID = "txtIssuedFrom" + i.ToString();
myPanel.Controls.Add(mylabel6_1);
myPanel.Controls.Add(myTextBox6_1);
Label myLabel7 = new Label();
myLabel7.ID = "lblDateOfIssuePass " + i.ToString();
myLabel7.Text = "Дата на издаване на международен паспорт:";
TextBox myTextBox7 = new TextBox();
myTextBox7.ID = "txtDateOfIssuePass" + i.ToString();
myPanel.Controls.Add(myLabel7);
myPanel.Controls.Add(myTextBox7);
Label myLabel7_1 = new Label();
myLabel7_1.ID = "lblPassportNum" + i.ToString();
myLabel7_1.Text = "Номер на паспорт:";
TextBox myTextBox7_1 = new TextBox();
myTextBox7_1.ID = "txtPassportNum" + i.ToString();
myPanel.Controls.Add(myLabel7_1);
myPanel.Controls.Add(myTextBox7_1);
Label myLabel8 = new Label();
myLabel8.ID = "lblDateOfExpiryPass " + i.ToString();
myLabel8.Text = "Дата на валидност на международен паспорт:";
TextBox myTextBox8 = new TextBox();
myTextBox8.ID = "txtDateOfExpiryPass" + i.ToString();
myPanel.Controls.Add(myLabel8);
myPanel.Controls.Add(myTextBox8);
Label myLabel9 = new Label();
myLabel9.ID = "lblHomeContact" + i.ToString();
myLabel9.Text = "Домашен телефон";
TextBox myTextBox9 = new TextBox();
myTextBox9.ID = "txtHomeContact" + i.ToString();
myPanel.Controls.Add(myLabel9);
myPanel.Controls.Add(myTextBox9);
Label myLabel10 = new Label();
myLabel10.ID = "lblMobContact" + i.ToString();
myLabel10.Text = "Мобилен телефон";
TextBox myTextBox10 = new TextBox();
myTextBox10.ID = "txtMobContact" + i.ToString();
myPanel.Controls.Add(myLabel10);
myPanel.Controls.Add(myTextBox10);
Label myLabel11 = new Label();
myLabel11.ID = "lblEmail" + i.ToString();
myLabel11.Text = "E-mail адрес";
TextBox myTextBox11 = new TextBox();
myTextBox11.ID = "txtEmail" + i.ToString();
myPanel.Controls.Add(myLabel11);
myPanel.Controls.Add(myTextBox11);
Label myLabel12 = new Label();
myLabel12.ID = "lblAddress" + i.ToString();
mylabel2.Text = "Адрес";
TextBox myTextBox12 = new TextBox();
myTextBox12.ID = "txbAddress" + i.ToString();
myPanel.Controls.Add(myLabel12);
myPanel.Controls.Add(myTextBox12);
}
}
You are missing one more step. Now add your panel control to another control container or at least your page control.
You have created a panel and addet the others controls on it,
but you forgot to add this created panel (myPanel) to your form.
Youre missing the following line of code:
myForm.Controls.Add(myPanel);
Change myForm to the name of your form.

Resources