Inward.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="pono" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField SelectText="Update" ShowSelectButton="True" />
<asp:BoundField DataField="pono" HeaderText="pono" ReadOnly="True" SortExpression="pono" />
<asp:BoundField DataField="podate" HeaderText="podate" SortExpression="podate" />
<asp:BoundField DataField="partyname" HeaderText="partyname" SortExpression="partyname" />
<asp:BoundField DataField="flag" HeaderText="flag" SortExpression="flag" />
<asp:BoundField DataField="itemnm" HeaderText="itemnm" SortExpression="itemnm" />
<asp:BoundField DataField="indt" HeaderText="indt" SortExpression="indt" />
<asp:BoundField DataField="qty" HeaderText="qty" SortExpression="qty" />
</Columns>
</asp:GridView>
inward.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string pono = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Update_inward.aspx?pono="+pono);
}
update_inward.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string stcon = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(stcon);
con.Open();
String query = "Select * from maxus_in where pono=" + Request.QueryString["pono"];
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TextBox1.Text = ds.Tables[0].Rows[0]["pono"].ToString();
TextBox2.Text = ds.Tables[0].Rows[0]["podate"].ToString();
TextBox3.Text = ds.Tables[0].Rows[0]["partyname"].ToString();
TextBox4.Text = ds.Tables[0].Rows[0]["itemnm"].ToString();
}
con.Close();
}
How do i transfer this data and display in textboxes in another page??
You can Use Query String or store value in the session and retrieve the value on page load of the next page.
username.Value = Request["username"];
username.Value = Session["username"].toString();
Related
I tried many work around but unable to set the column as hyperlink. This is the output i get.
Output that i get
I want to add the hyperlink as below screenshot:
Output with hyperlink
Click on that link able to show the detail as below
This is my code but i unable to add hyperlink:
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat = "server" AutoGenerateColumns="false" OnDataBound="OnDataBound" GridLines="Both">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="150" />
<asp:BoundField DataField="LOT" HeaderText="LOT" ItemStyle-Width="150" />
<asp:BoundField DataField="TYPE" HeaderText="TYPE" ItemStyle-Width="150" />
<asp:BoundField DataField="KEY" HeaderText="KEY" ItemStyle-Width="150" />
<asp:BoundField DataField="VALUE" HeaderText="VALUE" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
Code behind that i have done:
protected void btn_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DateTime StartDate = Convert.ToDateTime(datepickerstart.Text);
string Date = StartDate.ToString("dd-MMM-yyyy");
DateTime EndDate = Convert.ToDateTime(datepicker.Text);
string dt2 = EndDate.ToString("dd-MMM-yyyy");
GridView1.DataSource = GetData("Oracle query");
GridView1.DataBind();
txtDate.Text = "You Selected Start:" + Date;
txtDate1.Text = "You Selected End:" + EndDate;
}
private DataTable GetData(string query)
{
string oradb = "Data Source=(DESCRIPTION =" +
"(ADDRESS = (PROTOCOL=TCP)(HOST = '')(PORT = ''))" +
"(CONNECT_DATA =" +
"(SERVER = DEDICATED)" +
"(SERVICE_NAME = '')" +
")" +
");User ID='';Password='';";
DataTable dt = new DataTable();
OracleConnection conn = new OracleConnection(oradb);
using (OracleConnection con = new OracleConnection(oradb))
{
using (OracleCommand cmd = new OracleCommand(query))
{
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void OnDataBound(object sender, EventArgs e)
{
for (int rowIndex = GridView1.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = GridView1.Rows[rowIndex];
GridViewRow previousRow = GridView1.Rows[rowIndex + 1];
if (row.Cells[0].Text == previousRow.Cells[0].Text)
{
row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 :
previousRow.Cells[0].RowSpan + 1;
previousRow.Cells[0].Visible = false;
}
}
}
}
Instead of Bound Field you need to use TemplateField > ItemTemplate > LinkButton just i have used below:
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat = "server" AutoGenerateColumns="false" OnDataBound="OnDataBound" GridLines="Both">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnIdLink" runat="server" Text='<%# Bind("ID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LOT" HeaderText="LOT" ItemStyle-Width="150" />
<asp:BoundField DataField="TYPE" HeaderText="TYPE" ItemStyle-Width="150" />
<asp:BoundField DataField="KEY" HeaderText="KEY" ItemStyle-Width="150" />
<asp:BoundField DataField="VALUE" HeaderText="VALUE" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
i have add link button in GridView , but in RowUpdaing method it is showing error , that is, does not contain a definition for 'gvReportCrime_RowUpdating' and no extension method 'gvReportCrime_RowUpdating' accepting a first argument of type does not contain a definition for 'gvReportCrime_RowUpdating' and no extension method 'gvReportCrime_RowUpdating' accepting a first argument of type ... here is my Admin.aspx page , and Admin.aspx.cs page code
<asp:GridView ID="gvReportCrime" runat="server" DataKeyNames="id" OnPageIndexChanging="gvReportCrime_PageIndexChanging" OnRowCancelingEdit="gvReportCrime_RowCancelingEdit" OnRowDeleting="gvReportCrime_RowDeleting" OnRowEditing="gvReportCrime_RowEditing" OnRowUpdating="gvReportCrime_RowUpdating" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CNIC" HeaderText="CNIC" />
<asp:BoundField DataField="Phone1" HeaderText="Phone1" />
<asp:BoundField DataField="Phone2" HeaderText="Phone2" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Gender" HeaderText="Gender" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="CrimeType" HeaderText="CrimeType" />
<asp:BoundField DataField="CrimeDetail" HeaderText="CrimeDetail" />
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
private void BindData()
{
MySqlConnection conn = new MySqlConnection();
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select * from reportCrime", conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvReportCrime.DataSource = ds;
gvReportCrime.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvReportCrime.DataSource = ds;
gvReportCrime.DataBind();
int columncount = gvReportCrime.Rows[0].Cells.Count;
gvReportCrime.Rows[0].Cells.Clear();
gvReportCrime.Rows[0].Cells.Add(new TableCell());
gvReportCrime.Rows[0].Cells[0].ColumnSpan = columncount;
gvReportCrime.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvReportcrime_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
MySqlConnection conn = new MySqlConnection();
String CNIC = Convert.ToString(gvReportCrime.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow) gvReportCrime.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox txtName = (TextBox)row.Cells[0].Controls[0];
TextBox txtPhone1 = (TextBox)row.Cells[1].Controls[0];
TextBox textPhone2 = (TextBox)row.Cells[2].Controls[0];
TextBox textEmail = (TextBox)row.Cells[3].Controls[0];
TextBox textGemder = (TextBox)row.Cells[4].Controls[0];
TextBox textAddress = (TextBox)row.Cells[5].Controls[0];
TextBox textCity = (TextBox)row.Cells[6].Controls[0];
TextBox textCrimeType = (TextBox)row.Cells[7].Controls[0];
TextBox textCrimeDetail = (TextBox)row.Cells[8].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
gvReportCrime.EditIndex = -1;
conn.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM reportcrime", conn);
MySqlCommand cmd = new MySqlCommand("update reportcrime set Name='" + Name + "',Phone1='" + Phone1 + "',Phone2='" + Phone2 + "',Email='" + Email + "',Gender='" + Gender + "',City='" + City + "',Address='" + Address + "',CrimeType='" + CrimeType + "',CrimeDetail='" + CrimeDetail + "' WHERE CNIC = '" + CNIC + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
gvReportCrime.DataBind();
}
I have a GridView that shows a list of restaurants and it's data from my database. In the last column I have a ButtonField. When the user clicks on the button, then the RowCommand fires and another GridView appears with the selected restaurant's reviews.
The issue I am having is that while the RowCommand event is fired, the second GridView gvReviews does not show up at all.
I have tried to set the GridView's visible to true but that does not
seem to work.
I have tried to use a TemplateField with a Button instead but that doesn't work either.
I have tried using if (!IsPostback) statement
Here's a snippet of my GridViews:
<asp:GridView ID="gvRestaurants" runat="server" AutoGenerateColumns="false" OnRowCommand="gvRestaurants_RowCommand">
<Columns>
<asp:BoundField DataField="RestaurantID" HeaderText="ID" />
<asp:BoundField DataField="RestName" HeaderText="Restaurant" />
<asp:BoundField DataField="RestAddr" HeaderText="Address" />
<asp:BoundField DataField="RestCity" HeaderText="City" />
<asp:BoundField DataField="RestState" HeaderText="State" />
<asp:BoundField DataField="RestZip" HeaderText="Zip Code" />
<asp:BoundField DataField="CategoryDesc" HeaderText="Category" />
<asp:ButtonField HeaderText="Reviews" CommandName="viewReviews" Text="View" ButtonType="Button" />
</Columns>
</asp:GridView>
<asp:GridView ID="gvReviews" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RestaurantID" HeaderText="ID" />
<asp:BoundField DataField="RestName" HeaderText="Restaurant" />
<asp:BoundField DataField="ReviewDate" HeaderText="Date of Review" />
<asp:BoundField DataField="FoodQuality" HeaderText="Food Quality" />
<asp:BoundField DataField="ServiceRating" HeaderText="Service" />
<asp:BoundField DataField="AtmosphereRating" HeaderText="Atmosphere" />
<asp:BoundField DataField="PriceRating" HeaderText="Price" />
<asp:BoundField DataField="ReviewText" HeaderText="Review" />
</Columns>
</asp:GridView>
Here's a snippet of the aspx.cs
protected void btnSearch_Click(object sender, EventArgs e)
{
gvRestaurants.Visible = true;
gvAllRestaurants.Visible = false;
DataSet ds = p.SearchByCategory(ddCategories.SelectedItem.Value, ddCategories2.SelectedItem.Value);
gvRestaurants.DataSource = ds;
gvRestaurants.DataBind();
}
protected void gvRestaurants_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "viewReviews")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvRestaurants.Rows[index];
int restID = int.Parse(row.Cells[0].Text);
gvReviews.DataSource = p.GetReview(restID);
gvReviews.DataBind();
gvRestaurants.Visible = false;
gvReviews.Visible = true;
}
else
{
string error = "There are no reviews for this restaurant.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + error + "');", true);
}
Here's a snippet of the methods i used:
public DataSet SearchByCategory(string category1, string category2)
{
DBConnect objDB = new DBConnect();
objCmd.Parameters.Clear();
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "GetRestaurantByCategory";
SqlParameter sqlParameter = new SqlParameter("#theCategory", category1);
SqlParameter sqlParameter2 = new SqlParameter("#theCategory2", category2);
sqlParameter.Direction = ParameterDirection.Input;
sqlParameter.SqlDbType = SqlDbType.VarChar;
sqlParameter.Size = 50;
sqlParameter2.Direction = ParameterDirection.Input;
sqlParameter2.SqlDbType = SqlDbType.VarChar;
sqlParameter2.Size = 50;
objCmd.Parameters.Add(sqlParameter);
objCmd.Parameters.Add(sqlParameter2);
objDB.GetConnection().Open();
DataSet ds = objDB.GetDataSetUsingCmdObj(objCmd);
objDB.CloseConnection();
return ds;
}
public DataSet GetReview(int restaurant)
{
DBConnect objDB = new DBConnect();
objCmd.Parameters.Clear();
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "GetReviewByRestaurantID";
SqlParameter sqlParameter = new SqlParameter("#theRestaurantID", restaurant);
sqlParameter.Direction = ParameterDirection.Input;
sqlParameter.SqlDbType = SqlDbType.Int;
sqlParameter.Size = 4;
objCmd.Parameters.Add(sqlParameter);
objDB.GetConnection().Open();
DataSet ds = objDB.GetDataSetUsingCmdObj(objCmd);
objDB.CloseConnection();
return ds;
}
Here are my stored procedures used:
CREATE PROCEDURE [dbo].GetRestaurantByCategory
#theCategory varchar(50),
#theCategory2 varchar(50)
AS
SELECT rest.RestaurantID, rest.RestName, rest.RestAddr, rest.RestCity, rest.RestState, rest.RestZip, cat.CategoryDesc
FROM Restaurants rest JOIN Categories cat ON rest.CategoryID = cat.CategoryID
WHERE CategoryDesc = #theCategory OR CategoryDesc = #theCategory2
CREATE PROCEDURE [dbo].GetReviewByRestaurantID
#theRestaurantID int
AS
SELECT rest.RestaurantID, rest.RestName, rev.ReviewDate, rev.FoodQuality, rev.ServiceRating, rev.AtmosphereRating, rev.PriceRating, rev.ReviewText
FROM Restaurants rest JOIN Reviews rev ON rest.RestaurantID = rev.RestaurantID
WHERE Rest.RestaurantID = #theRestaurantID
Your GridView doesn't show because you bind it to a DataSet instead of binding it directly to a DataTable within this DataSet.
Try changing this line:
gvReviews.DataSource = p.GetReview(restID);
To this:
gvReviews.DataSource = p.GetReview(restID).Tables[0];
use this query
SELECT rest.RestaurantID, rest.RestName, rev.ReviewDate, rev.FoodQuality, rev.ServiceRating, rev.AtmosphereRating, rev.PriceRating, rev.ReviewText
FROM Restaurants rest JOIN Reviews rev ON rev.RestaurantID = rest.RestaurantID
WHERE Rest.RestaurantID = #theRestaurantID
I was working on my project in which i have grid view of which there is a status field which has button in it .
When user clicks on that button the text of that button gets changed from pending to confirm .
The problem is that when I close the browser and load the .aspx page again through visual studio the text of the button again gets set to pending which i does not want.
Can any one tell me how to keep the button text to confirm only once the button get clicked and also when I click on first row status field button all the rest status field gets updated with confirm status in database.
Here is my code: (Front End Code)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
Font-Bold="True" Font-Size="Small" GridLines="None">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
<asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
<asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
<asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
<asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
<asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
<asp:TemplateField HeaderText="Status Field">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
Text="Pending" BorderStyle="None" Font-Bold="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
(Back end Code):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lst = new List<string>() { "asd", "xxx" };
GridView1.DataSource = lst;
this.BindGrid();
}
}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
Response.Redirect("~/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Session.Clear();
Response.Redirect("~/Admin Panel/LoginForm.aspx");
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT packagename,name, gender,mobileno,email,noofdays,child,adults FROM enquiry"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MYCOMMAND")
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True");
string sql;
Button Button1 = (Button)e.CommandSource;
if (Button1 != null)
Button1.Text = "Confirm";
sql = "update enquiry set statusfield='" + Button1.Text + "'";
SqlCommand comm = new SqlCommand(sql, con);
con.Open();
comm.ExecuteNonQuery();
}
}
You can use the Bind function from asp.net so your button text will be taken from DB result. like below.
In aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
Font-Bold="True" Font-Size="Small" GridLines="None">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="enquiryid" HeaderText="Enquiryid" />
<asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
<asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
<asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
<asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
<asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
<asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
<asp:TemplateField HeaderText="Status Field">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
Text='<%# Bind("statusfield")%>' BorderStyle="None" Font-Bold="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .cs file modify your BindGrid method, so that it can return the statusfield column.
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT enquiryid,packagename,name, gender,mobileno,email,noofdays,child,adults,statusfield FROM enquiry"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
I'm building a site but there is a problem.
I don't know how I can access that data of grid in which row the button is clicked.
.aspx file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlEntry"
CssClass="style1">
<Columns>
<asp:BoundField DataField="ReordID" HeaderText="ReordID" InsertVisible="False" SortExpression="ReordID"
Visible="False" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="EmailID" HeaderText="EmailID" SortExpression="EmailID" />
<asp:BoundField DataField="Password" HeaderText="Password" SortExpression="Password" />
<asp:TemplateField HeaderText="Delete" SortExpression="Delete">
<ItemTemplate>
<asp:Button Text="Delete" runat="server" OnClick="Grid_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
<asp:SqlDataSource ID="SqlEntry" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Entry]"></asp:SqlDataSource>
.CS file:
protected void Refresh_Click(object sender, EventArgs e)
{
GridView1.DataBind();
resetdata();
}
protected void Submit_Click(object sender, EventArgs e)
{
string str = "INSERT INTO Entry (Name, EmailID, Password) VALUES ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "');";
Connection conn = new Connection(str);
Refresh_Click(sender, e);
}
protected void resetdata()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
protected void Grid_Click(Object sender, EventArgs e)
{
string str = "DELETE FROM Entry WHERE RecordID = #RecordID";
Connection conn = new Connection(str);
GridView1.DataBind();
resetdata();
}
Connection Class:
public Connection(string qry)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = qry;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
How can I delete the data from SQL Server 2005 using this webpage?
What is the problem in the code?
You could attach a CommandArgument and a CommandName to your button that contains the ID -
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument="<%# Eval('ReordID') %>" CommandName="REMOVE" OnClick="Grid_Click" />
</ItemTemplate>
... then add a RowCommand event to the GridView -
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="REMOVE")
{
int orderId = Convert.ToInt32(e.CommandArgument);
//Do Sql Here
}
}