I got a 'grid view' and three buttons in my web form. Now when I click 'button1' I want to show the respective result for query1 in 'grid view' and for 'button2' it should show the result of query2. Same for button3.
HTML of my web form :
<%# Page Title="" Language="C#" MasterPageFile="~/Master Page/Site1.Master" AutoEventWireup="true" CodeBehind="Dashboard.aspx.cs" Inherits="onlineshopping.Master_Page.WebForm1" %>
<asp:Content ID="Content1" runat="server" contentplaceholderid="BillingContent">
<div>
<table>
<tr>
<td>
<asp:Button ID="btn_dsbrdItems" runat="server" Text="Show Items" />
</td>
<td style="width:20px"></td>
<td>
<asp:Button ID="btn_dsbrdShowInvoices" runat="server" Text="Show Invoices" />
</td>
<td style="width:20px"></td>
<td>
<asp:Button ID="btn_dsbrShowUsers" runat="server" Text="Show Users" />
</td>
<td style="width:20px"></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:GridView ID="gv_dashboard" runat="server" AutoGenerateColumns="false">
</asp:GridView>
</td>
</tr>
</table>
I know that I can bind a query result to 'grid view' and I have done that before. But I don't know what to do to achieve this. And I tried something. I knew its stupid & not gonna work. Still I just tried and didn't work as I expected. This is what I tried.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace onlineshopping.Master_Page
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionstring").ToString());
string sql = "";
DataSet ds = new DataSet();
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void btn_dsbrdItems_Click(object sender, EventArgs e)
{
if(con.State==ConnectionState.Closed)
{ con.Open(); }
sql = "select * from item";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
protected void btn_dsbrdShowInvoices_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{ con.Open(); }
sql = "select * from invoice";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
protected void btn_dsbrShowUsers_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{ con.Open(); }
sql = "select * from tbl_users";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
}
}
This is my web form
I am using 'master page' for side 'menu'. If this question is asked before please help me to find that link. I couldn't find.
Related
and thank you for taking the time to read my post! It is very much appreciated. I am pretty new to ASP.Net and I am trying to create a simple page where I can search a table on my SQL Server database.
Here is the asp.net code:
<%# Page Language="C#" MasterPageFile="~/PantryAdmin.Master" AutoEventWireup="true" CodeFile="ProductSearch.aspx.cs" Inherits="RampantryF.ProductSearch" %>
<asp:Content runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<div>
<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:fall16_g8ConnectionString %>" SelectCommand="SELECT * FROM [PRODUCT]"></asp:SqlDataSource>
</div>
</asp:Content>
My code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RampantryF
{
public partial class ProductSearch : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["fall16_g8ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from PRODUCT where(PRODUCT_NAME like '%' + #PRODUCT_NAME + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#PRODUCT_NAME", SqlDbType.NVarChar).Value = SearchBox.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "PRODUCT_NAME");
GridView2.DataSource = ds;
GridView2.DataBind();
con.Close();
}
}
}
The page loads fine but when you press the 'search' button it just refreshes the page instead of loading the data into the gridview. I am wondering what is going on and how I can fix it.
Let me know if any other information is needed. I am happy to provide it.
Thank you!
few changes done to your code, check how the like parameter assigned
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from PRODUCT where PRODUCT_NAME like #PRODUCT_NAME";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#PRODUCT_NAME", SqlDbType.NVarChar).Value = "%"+ SearchBox.Text + "%";
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds, "PRODUCT_NAME");
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
Also change the AutoGenerateColumns as true in the aspx page.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.
Here is the code that I used
.aspx code
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<h2>Employee Details</h2>
</td>
</tr>
<tr>
<td>ID</td>
<td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>BloodGroup</td>
<td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Emergency Contact No.</td>
<td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Photo:</td>
<td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />
<asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />
<asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'
Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Image_upload
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileuploadEmpImage.HasFile)
{
int length = fileuploadEmpImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadEmpImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
int id = Convert.ToInt32(txtID.Text);
string name = txtName.Text;
string bloodGroup = txtBloodGroup.Text;
string phoneNo = txtContactNo.Text;
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtBloodGroup.Text = string.Empty;
txtContactNo.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
BindGridData();
}
}
}
private void BindGridData()
{
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
grdEmployee.DataSource = dt;
grdEmployee.DataBind();
}
}
}
handler.ashx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Image_upload
{
public class Employeeimage_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
MySqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.
To fix your code introduce MySqlParameters:
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
var connection = new MySqlConnection(
ConfigurationManager.ConnectionString["database"]);
connection.Open();
// remove the order by and add a where with a parameter placeholder
var command = new MySqlCommand(
"select ImageI from database.employee where id = #id",
connection);
// setup parameter and add to command
command.Parameters.AddWithValue("#id", imageid);
// execute
MySqlDataReader dr = command.ExecuteReader();
// rest of your code
}
Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files
I am new to Asp.Net & C#. I am developing a blog. I am able to save images in a folder and the image path in SQL Server. Now I want to retrieve the image from folder whose path is stored in SQL Server table.
I try this:
ASPX markup:
<body>
<form id="form1" runat="server">
<div class="row">
<div class="page-header"></div>
<div class="col-lg-3">
<asp:Image ID="Image1" CssClass="img-thumbnail" runat="server" />
</div>
</div>
</form>
</body>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace Admin_Panel
{
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
Image1.ImageUrl ="~/Images/" + filep;
}
con.Close();
}
}
}
But the above code will only show one image.
What I want: I want to show all images using a foreach loop or something like a loop, but I don't know how to do that.
Any help will be appreciated.
First of all, you should use asp.repeater:
<asp:Repeater ID="RptImages" runat="server">
<ItemTemplate>
<asp:Image ID="Img" runat="server" ImageUrl='<%# Container.DataItem %>'/>
</ItemTemplate>
</asp:Repeater>
Else:
public partial class Admin : System.Web.UI.Page
{
List<String> images = new List();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
images.add(String.Concat("~/Images/", filep);
}
con.Close();
RptImages.DataSource = images;
RptImages.DataBind();
}
}
help me please. I'm a newbie. Found this solution here too. The authentication worked but the redirection part doesn't. It always redirects to Default.Aspx tho the admins should be redirected to Add.aspx Please help :'( Thanks in advance!
Here's my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace CRUD
{
public partial class Login1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["employee1ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("select * from userdata where username=#username and password=#password", objsqlconn);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["permission"].ToString() == "admin")
Response.Redirect("Add.aspx");
else
Response.Redirect("Default.aspx");
}
else
{
Label1.Text = "Invalid username or password. Please try again.";
}
}
}
}
and...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Login1.aspx.cs" Inherits="CRUD.Login1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<p class="style1">
LOG IN</p>
<p class="style1">
</p>
<p class="style1">
Username:
<asp:TextBox ID="TextBox1" runat="server" Width="167px"></asp:TextBox>
</p>
<p class="style1">
Password:
<asp:TextBox ID="TextBox2" runat="server" Width="167px"></asp:TextBox>
</p>
<p class="style1">
Not a member yet? Click
here
.
Table structure:
db: userdata
-username
-password
-permission
You are giving both the textbox1 value to password as well. make the changes as below
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
Please put your code in proper syntax and check:-
protected void Button1_Click(object sender, EventArgs e)
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["employee1ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("select * from userdata where username=#username and password=#password", objsqlconn);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["permission"].ToString() == "admin")
{
Response.Redirect("Add.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
Label1.Text = "Invalid username or password. Please try again.";
}
}
I am retrieving Data From Database into GridView.
I don't know how to Edit and Delete row in GridView and it Also Update in Database.
Also please Tell me if their is any mistake in my Code
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 248px;
}
.style2
{
width: 100%;
}
.style3
{
height: 180px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style3">
<h1 align="center">Students Personal Information
</h1>
<table class="style2">
<tr>
<td class="style1">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Button ID="Button1" runat="server" Text="Insert Data"
onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Students" Width="128px" />
</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
enter code here
And my back-end code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=DATA_NET_81_SOF;Initial
Catalog=Students;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Student's Name";
Label2.Text = "Student's Class";
Label3.Text = "Student's Roll Number";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", conn);
conn.Open();
cmd.Parameters.AddWithValue("StudentName", TextBox1.Text);
cmd.Parameters.AddWithValue("StudentClass", TextBox2.Text);
cmd.Parameters.AddWithValue("StudentRollno", TextBox3.Text);
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand sql = new SqlCommand("Select * from Personalinfo", conn);
SqlDataAdapter da = new SqlDataAdapter(sql);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = (ds);
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
}
private string connection = #"...";
protected void Button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connection))
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
}
For Update -->
protected void Button_Update(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "UPDATE Personalinfo SET StudentName = #1 ... WHERE Student_Id= #N";
cmd.Parameters.Add("#1",SqlDbType.NVarChar).Value = your_value;
cmd.Para.....
cmd.Parameters.Add("#N",.....).Value = your_student_id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
For Delete -->>
protected void Button_Delete(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Personalinfo WHERE StudentName = '"+TextBox1.Text+"'";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
After every event of button you can make a BindGrid ... to refresh your data from data grid... in BindGrid method you need to remake the select method you just did ... if you have issue tell me