Display Gridview Tables based on dropdown value selection using asp.net - c#

I have a dropdown value which selects customer name and also i have a
sales executive dropdown which selects executives name i want to
display Gridview table based on customer name selection but i am able
to display only its ID . i need to display their names instead of ID.
<div class="form-group">
<asp:Label class="control-label col-md-3 col-sm-3 col-xs-12" runat="server" Text="Customer Name"></asp:Label>
<div class="col-md-7 col-sm-6 col-xs-12">
<asp:DropDownList ID="customerDetails" runat="server" class="form-control col-md-7 col-xs-12" CssClass="mydropdownlist">
<asp:ListItem Enabled="true" Value="0">--Select Customer--</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="form-group">
<asp:Label class="control-label col-md-3 col-sm-3 col-xs-12" runat="server" Text="Sales Executive"></asp:Label>
<div class="col-md-7 col-sm-6 col-xs-12">
<asp:DropDownList ID="salesExceutive" runat="server" class="form-control col-md-7 col-xs-12" CssClass="mydropdownlist">
<asp:ListItem Enabled="true" Value="0">--Select Sales Executive--</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<asp:Button ID="btnSearch" class="btn btn-primary"
runat="server" Text="Search" OnClick="btnSearch_Click" />
I have tried following.
protected void btnSearch_Click(object sender, EventArgs e)
{
if (customerText != "0" && salesExeText == "0")
{
string sqlQuery = #"SELECT * from app_order_master where
customer_id = " + customerText ;
using (DataTable dt = SMSDBHelperFE.ExecuteReaderDataTable(CommandType.Text, sqlQuery, null))
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
See the picture above instead of id i need to display name

Your Question is not fully understandable. But I think you are storing Customer Id in the table. And while retrieving data from app_order_master table and binding with gridview you are not Joining it with Customer table with the id. That's why you are not getting Customer name.As I don't know your table structure I couldn't help much.But you can self learn about joining from below link
https://www.w3schools.com/sql/sql_join.asp
http://www.sql-join.com/sql-join-types
https://www.tutorialspoint.com/sql/sql-using-joins

Related

How to display 10 recent news from database using Bootstrap?

I wanted to display 10 recent news from database. I have used LIMIT 10 in sql query to display 10 recent news. I am using bootstrap.
I am getting only 1 news from the database. I know that here I have to use datalist or listview in design. But I don't know how to implement it using Bootstrap.
Default.aspx:
<div class="container">
<h1 class="main-module-title">Recent <span>News</span></h1>
<%-- <asp:datalist runat="server">
<ItemTemplate>--%>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail"/>
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><asp:Label ID="newsheader" runat="server" Text=""></asp:Label></h4>
<p runat="server" style="text-align:justify" id="newscontent"> </p>
</div>
</div>
<hr/>
</div>
<%-- </ItemTemplate>
</asp:datalist>--%>
</div>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySqlConnection conn = null;
string newsitem = null;
if (!(Request.QueryString["newstitle"] == null))
{
Page.Header.Title = Request.QueryString["newstitle"] + " - DubaiExporters ";
}
else
{
Page.Header.Title = "DubaiExporters - Dubai Business News - UAE Exports";
}
try
{
string connStr = ConfigurationManager.ConnectionStrings["mysqldbeConnectionString"].ToString();
string newssql = null;
newssql = "SELECT * FROM news WHERE status = b'1' AND linkstatus = b'1' ORDER BY datepublished DESC LIMIT 10";
conn = new MySqlConnection(connStr);
MySqlCommand cmd = new MySqlCommand(newssql, conn);
conn.Open();
MySqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(r.Read())//while(r.Read())
{
newsheader.Text = HttpUtility.HtmlDecode(r["newstitle"].ToString().Trim()).ToString();
newscontent.InnerHtml = HttpUtility.HtmlDecode(r["newsbrief"].ToString().Trim()).ToString();
ImgNews.ImageUrl = "~/images/newspictures/" + r["image"].ToString();
}
}
catch (MySqlException ex)
{
}
catch (Exception ex)
{
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
try the below template and bind the DataList to DataSource in the Page Load event inside !Page.IsPOstBack condition
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail" ImageUrl='<%# "~/images/newspictures/" + Eval("image")%>' />
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><a href="#">
<asp:Label ID="newsheader" runat="server" Text='<%# Eval("newstitle") %>'></asp:Label></a></h4>
<p runat="server" style="text-align: justify" id="newscontent"><%# Eval("newsbrief") %></p>
</div>
</div>
<hr />
</div>
</ItemTemplate>
</asp:DataList>

how to manually insert value in textbox which not replace automatically in slider extension

We are using Slider Extender control when we are manually insert into textbox which is boundControlID of that slider Extender control
The slider min value is 1 and max value is 50 if I change manually into boundcontrolID textbox “ 25 “ the slider move to 25 but when I insert 55 it will move 50 and in textbox 55 replace by 50 automatically, but I want that 55 should not be replaced.
Here is some code:
<div class="row">
<div class="col-md-12">
<div class="col-md-2"> </div>
<div class="col-md-3"><asp:Label ID="Label1" runat="server" Text="Size" CssClass="FormLabel"></asp:Label></div>
<div class="col-md-2">
<cc1:SliderExtender
ID="SliderExtender1"
runat="server"
TargetControlID="TextBox1"
BoundControlID="TextBox2"
Minimum="1"
Maximum="50"
>
</cc1:SliderExtender>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
</div>
<div class="col-md-2"><asp:TextBox ID="TextBox2" runat="server" CssClass="Textbox" OnTextChanged="TextBox2_TextChanged" ></asp:TextBox><asp:Label ID="Label17" runat="server" Text="Sorry You Enter Size is above 50 TB" Visible="false" ForeColor="Red" Font-Names="Segoe UI"></asp:Label></div>
<div class="col-md-3"> </div>
</div>
</div>
C# code :
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
try
{
TextBox1.Text = TextBox2.Text;
SliderExtender1.DataBind();
}
catch(Exception ex)
{
ex.Message.ToString();
}
}
Thanks for help.

Asp.net Multiple File Uploads

I have an ASP.net web application which saves all details entered in the session and at the end, sends an email with all the details including an attachment of the file uploaded (all this currently works fine).
The issue I have is that a change is required to the file upload page. I want to now be able to upload multiple docs, but separately, so basically the user finds the file to upload then clicks an 'Add' button. The upload file field should then clear and a table should populate with the uploaded file(s) with a 'Remove/Delete' button for each file uploaded.
The details that should be displayed in this table are:
File name
Option selected form the new dropdown list
Remove button
As I said I have single file upload working using the code behind but I have no idea how to implement what I'm after so that all uploaded doc's are sent in my email.
Current HTML
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput" style="background-color: #ededed">
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new">
<span class="glyphicon glyphicon-folder-open" title="Click to select a file."></span>
</span>
<span class="fileinput-exists">
<span class="glyphicon glyphicon-folder-open" title="Click to change the selected file."></span>
</span>
<input type="file" name="..." id="fuAttachment" runat="server" />
</span>
</div>
</div>
<div class="col-sm-3">
<asp:DropDownList ID="Step03WebTypeDD" runat="server" class="form-control">
<asp:ListItem Value="- - Please select - -">- - Please select - -</asp:ListItem>
<asp:ListItem Value="Requirements">Requirements</asp:ListItem>
<asp:ListItem Value="Functional specification">Functional specification</asp:ListItem>
<asp:ListItem Value="Page Content">Page Content</asp:ListItem>
<asp:ListItem Value="Page Designs">Page Designs</asp:ListItem>
<asp:ListItem Value="Page Designs">Other</asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-sm-1">
<asp:LinkButton ID="UploadAddButton" runat="server" OnClick="Step05UploadAddButton_Click" CssClass="btn btn-success pull-right" ToolTip="Click to upload the file.">
<span class="glyphicon glyphicon-plus"></span> Add
</asp:LinkButton>
</div>
</div>
Current Code Behind
protected void Step05UploadAddButton_Click(object sender, EventArgs e)
{
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
Session["FileContent"] = content;
Session["FileContentType"] = file.ContentType;
Session["File"] = fuAttachment.PostedFile.FileName;
Session["AttachmentProvided"] = "Yes";
}
else
{
Session["FileContent"] = "";
Session["FileContentType"] = "";
Session["File"] = "";
Session["AttachmentProvided"] = "No";
}
}
My code behind does not capture the option selected but will need to so I can display it on my confirmation page (HTML shown below)
<div class="form-group">
<asp:Label ID="Label6" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Attachment provided:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<% if (Session["AttachmentProvided"] == "Yes")
{%>
Yes (<%=Session["File"] %>)
<%}
else
{ %>
No
<%} %>
</div>
</div>
You can use JavaScript to add additional <input type="file" /> elements to the DOM, and generically refer to all of the files using Request.Files as mentioned on MSDN. A sample taken from MSDN:
Files = Request.Files; // Load File collection into HttpFileCollection variable.
arr1 = Files.AllKeys; // This will get names of all files into a string array.
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("File: " + Server.HtmlEncode(arr1[loop1]) + "<br />");
Response.Write(" size = " + Files[loop1].ContentLength + "<br />");
Response.Write(" content type = " + Files[loop1].ContentType + "<br />");
}

Asp.Net SQL Delete Statement

I have an Asp.net application and I am trying to delete a row from my 'Users' db if the user submits the requests via the web but I can't seem to get it to work.
HTML
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Remove User</h3>
</div>
<div class="panel-body">
<asp:Label ID="lbRemoveUser" runat="server" Text="Remove User">
<b>Enter Full Name</b>
</asp:Label>
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist." Visible="false" style="color: red"></asp:Label>
</div>
<div class="panel-footer">
<div class="text-center">
<asp:Button CssClass="btn btn-danger" ID="btnSubmitRemoveUser" runat="server" Text="Remove User" ToolTip="Click to remove the user from the list." OnClick="removeUserSubmitButton_Click" />
</div>
</div>
</div>
<!-- Confirm Removal Modal-->
<div class="modal fade" id="confirmRemoveUserModal">
<div class="modal-dialog" style="margin-top: 55px">
<div class="modal-content">
<div class="modal-header ConfirmHeader">
<h4 class="modal-title" id="myModalLabel">Confirm Removal</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to remove <b><%=Session["txtRemoveUser"] %></b> from the payday lunch list?</p>
<p>If you don't, click 'No' and the user will not be removed.</p>
</div>
<div class="modal-footer ConfirmFooter">
<asp:Button id="btnRemoveConfirmYes" runat="server" CssClass="btn btn-success" Text="Yes" OnClick="btnRemoveConfirmYes_Click" ToolTip="Click to remove the user from the payday lunch list." />
<asp:Button id="btnRemoveConfirmNo" runat="server" CssClass="btn btn-warning" Text="No" OnClick="btnAllCloses_Click" ToolTip="Click to close this screen. The user will not be removed." />
</div>
</div>
</div>
</div>
Code I tried
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = " + txtRemoveUser.Text, conn);
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Like I said all I want is to delete the entry if it exists in my db. I already have a check to make sure that the entry exists in the 'Users' table
Do I need the SqlDataReader rd1 = cmd1.ExecuteReader(); as when I tried it, I got a server error "System.Data.SqlClient.SqlException: Invalid column name 'Test2'."
You are not using ExecuteNonQuery. You also have to wrap the user-name in apostrophes:
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = '" + txtRemoveUser.Text + "'", conn);
But you should always use sql parameters to prevent sql injection and other issues:
using(var cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn))
{
cmd1.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtRemoveUser.Text;
conn.Open();
cmd1.ExecuteNonQuery();
}
also use the using-statement on types that implement IDisposable like SqlCommand or -more important- SqlConnection to ensure that unmanaged resources are disposed.

Show product details in page

I need to show products details in a page.
My aspx is like below...
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img runat="server" id="img" alt="" src="" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a runat="server" id="name" href="single-product.html"></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div runat="server" id="price" class="price-current pull-right"></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
and my codebehind is like below...
dbConnection cn = new dbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getLoopData();
}
}
public void getLoopData()
{
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
while (reader.Read())
{
//int id = reader.GetInt32(0);
name.InnerText = reader["InventionName"].ToString();
price.InnerText = reader["Price"].ToString();
img.Src = reader["Picture"].ToString();
}
reader.Close();
cn.con.Close();
}
But it is showing only last product details.
How should I repeat the div for each product and how to show every products in page ??
You can use Asp Repeater to do that.
Check this link out : http://www.w3schools.com/aspnet/aspnet_repeater.asp
You need a datagrid control, repeater or similar to show tabular data.
Right now you only have one control per attribute to show all records, that's why last one wins.
Your view/page could be like this:
<asp:Repeater ID="ProductRepeater" runat="server" EnableViewState="False">
<ItemTemplate>
<div class="product-item">
<div class="image">
<img id="img" alt="" src='<%# Eval("Picture") %>' />
///...
</ItemTemplate>
</asp:Repeater>
In your code you could do this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "SELECT InventionName, Price, Picture FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
ProductRepeater.DataSource = reader;
ProductRepeater.DataBind();
You are iterating a list, and assigning data to name, price and img.Src, but you overwrite the values on each iteration, therefore you only have the values from the last element.
You should bind you data source (reader) to an <asp:Repeater>'s DataSource property. In your markup you specify a header (HeaderTemplate), a footer (FooterTemplate) and content (ItemTemplate). You can omit the header and footer template if you don't need them. You can also use an AlternatingItemTemplate if you need to do different things with odd/even rows (e.g. alternating row color in a table).
You can access properties of the databound datatype using the <%# Eval("SomeProperty") %> which is a databinding expression.
HTML markup would be something like this:
<asp:Repeater id="Products" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img class="img" alt="" src="<%# Eval("Picture") %>" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a class="name" href="single-product.html"><%# Eval("InventionName") %></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div class="price" class="price-current pull-right"><%# Eval("Price") %></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
and wire up the datasource in codebehind like this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
Products.DataSource = reader; // rather than iterating manually, you assign the datasource to the repeater.
Products.DataBind();
reader.Close();
cn.con.Close();
Side note: I changed the attribute from id to class on the name, price and img element. Because when this markup is rendered it would have been with multiple elements with the same id, which it shouldn't since id is supposed to be unique according to specification.

Categories