I am working on a project in which I am to display, insert, delete the data in my access database. I made buttons that will display a specific table from the database. I then made an asp column to display the delete button next to each row. The issue that I am trying to figure out is: How can I have it so that when the delete button is clicked the specific row is identified so then I may delete it? Any hints or tips are welcomed. Thank you.
<body>
<h1 class="center" style="text-align: center" >Display, Delete, and Add</h1>
<h3 id="Title1"></h3>
<style>
.center{
margin: 0 auto;
}
</style>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" class="center" runat="server" Width="300px" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
</p>
<p >
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Courses" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Student Information" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Students" />
</p>
<p>
</p>
<p>
</p>
<p>
</p>
</form>
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con = new OleDbConnection (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\achowdhary\Documents\Database1.accdb");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM COURSES", con);
DataSet set = new DataSet();
ada.Fill(set, "COURSES");
DataTable tab = new DataTable();
tab = set.Tables["COURSES"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENT_INFO", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENT_INFO");
DataTable tab = new DataTable();
tab = set.Tables["STUDENT_INFO"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENTS", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENTS");
DataTable tab = new DataTable();
tab = set.Tables["STUDENTS"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void btn1_Click(object sender, EventArgs e)
{
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "hello" + "');", true);
}
}
Many possibilites, my prefer is, bind a commandArgument in button with your identifier, and recover this value on post back
protected void btn1_Click(object sender, EventArgs e)
{
var identifier = ((Button)sender).CommandArgument;
}
Html
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click" CommandArgument='<%# Eval("PropertyName") %>'/>
</ItemTemplate>
Related
I have a richtextbox and a gridview.
When I enter the data into the richtextbox, it should be displayed in a gridview and saved in database.
Now my requirement is that, if i am entering a paragraph or a large amount of data I should display a "readmore" button, that when clicked, display the complete data.
<%# Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" />
<br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
c# code-
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(#Richtextbox)", con);
cmd.Parameters.AddWithValue("#Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
first in your select query add id of your text(your primary key of table RichTextBoxData)
and in gridview make it,s visible =false like this
<asp:TemplateField HeaderText="id" InsertVisible="False" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and then
protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lb =e.Row.FindControl("lbltxt") as Label;
if (lb.Text.Length > 15)//any length u want
{
DataRow drv = ((DataRowView)e.Row.DataItem).Row;
int tempID = Convert.ToInt32(drv["id"].ToString());
HyperLink hp = new HyperLink();
hp.Text = "read more";
hp.NavigateUrl = "~/mydetails.aspx?id=" + tempID;
e.Row.Cells[1].Controls.Add(hp);
lb.Text = lb.Text.Substring(0, 15);
}
}
}
and on page_load of mydetails.aspx make
query to select RichTextData where id=request.querystring["id"]
I want to add multiple category->subcategory-> sub-subcategory using nested repeater:
http://i.stack.imgur.com/bMiYZ.png
Similar to this but having more categories and sub-categories from database.
<form id="form1" runat="server">
<div>
<ul>
<asp:Repeater ID="outerRep" runat="server" OnItemDataBound="outerRep_ItemDataBound">
<ItemTemplate>
<li>
<asp:Label Font-Size="Large" Font-Bold="true" ID="lblCategoryName" runat="server" Text='<%# Eval("CategoryName") %>' />
</li>
<ul>
<asp:Repeater ID="innerRep" runat="server">
<ItemTemplate>
<li style="background-color: AliceBlue">
<asp:HyperLink ID="hlProductName" runat="server" Text='<%# Eval("SubCategoryName")%>' />
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</form>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection("Data Source=.; uid=sa; pwd=xxx;database=registration;");
SqlCommand myCommand = new SqlCommand("usp_GetProductsForCategories", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
// Attach the relationship to the dataSet
ds.Relations.Add(new DataRelation(
"CategoriesRelation",
ds.Tables[0].Columns["CategoryID"],
ds.Tables[1].Columns["CategoryID"]));
outerRep.DataSource = ds.Tables[0];
outerRep.DataBind();
}
protected void outerRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = e.Item.DataItem as DataRowView;
Repeater innerRep = e.Item.FindControl("innerRep") as Repeater;
innerRep.DataSource = drv.CreateChildView("CategoriesRelation");
innerRep.DataBind();
}
}
or any better way to do it? Please help.
I have the following in my page.
2 Asp Buttons
1 GridView
1 image button for export to excel
I need to view gridview based on respective buttons. i.e. Each button will have different data to displayed. Also gridview should allow paging as there are many records. Export to excel should also happen when image button is clicked including all pages in gridview. Can any one help in this ?
My code is following
aspx file.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<table id="Table2" width="100%" align="left" runat="server">
<tr>
<td class="auto-style8">
</td>
<td class="auto-style9"></td><td class="auto-style10">
<asp:Button ID="Admin" runat="server" Text="Admin" TOOLTIP="Sign In" TABINDEX="3" BackColor="Gray" BorderColor="Black" BorderStyle="Groove" Font-Bold="True" Font-Names="Arial" Font-Size="Large" ForeColor="White" Height="46px" Width="85px"/>
<asp:Menu ID="Menu1" runat="server" StaticSubMenuIndent="" Font-Bold="True" Font-Size="Large">
<Items>
<asp:MenuItem Text="Home" Value="Home" NavigateUrl="Admin_Main.aspx"></asp:MenuItem>
<asp:MenuItem Text="Add Customer" Value="Add Customer" NavigateUrl="Add_Details.aspx"></asp:MenuItem>
<asp:MenuItem Text="Delete Customer" Value="Delete Customer" NavigateUrl="Delete_Customer.aspx"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:LinkButton ID="logout" runat="server" OnClick="logout_click" Font-Bold="True" Font-Size="Large">Logout</asp:LinkButton>
</td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="UserName" Font-Bold="True"
Font-Size="X-Large"></asp:Label>
<asp:TextBox ID="userName" Name= "userName" runat="server" Font-Bold="True"></asp:TextBox>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="Email Log" OnClick= "Email_Click" Height="35px" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:Button ID="Button1" runat="server" Text="All Log" Height="35px" OnClick= "Log_Click" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:ImageButton ID="btnexport" runat="server" Height="35px" ImageUrl="~/Images/exp-xls.gif" Width="112px" OnClick="btnExport_Click" Visible="false" />
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Content>
aspx.cs file
public partial class Display_Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string user = (string)(Session["user"]);
if (!IsPostBack)
{
if (user == null)
{
Response.Redirect("~/InvalidLogin.aspx");
}
else
{
Admin.Text = user;
Admin.Enabled = false;
}
}
}
protected void Email_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" Select Customer_Name,Time_Send_Clicked,Reminder_Type from Email_Log where Username='{0}'",userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename=ActivityReport_" + userName.Text + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Log_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" SELECT [Activity],[Time],[Ticket_Number] FROM Log where Username='{0}'", userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void logout_click(object sender, EventArgs e)
{
this.Session["user"] = null;
this.Session["group"] = null;
Response.Redirect("~/Default.aspx");
}
}
To add pagging u need to specify AllowPaging="True" this will add pagging but it wont work until u specify this which handle the onclick event when page button is clicked
onpageindexchanging="GridView1_PageIndexChanging"
<asp:GridView ID="GridView1"AutoGenerateColumns="false" DataKeyNames="Identityrowoftable" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging" />
in code behind add this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// you need to rebind gridview here
//just set the source and databind
}
after this the print part
first you need to clear controls so unwanted elements dont come while print.
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
how to use ClearControl when exporting as excel
protected void btnExport_Click(object sender, EventArgs e)
{
// Reference your own GridView here
if (GridView1.Rows.Count > 65535)
{
//DisplayError("Export to Excel is not allowed" +
// "due to excessive number of rows.");
return;
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=nameofexcelfile_" + DateTime.Now+".xls" );
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
GridView1.PagerSettings.Visible = false;
ClearControls(GridView1);
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView1GridView1);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
this will print records without paging buttons
I have Template Field for gridview as below:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
When i am in gv_RowUpdating event, i wanted to take the value of edited field by findcontrol.
For that i am using following code:
`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
But each time it is showing me null value in txtUname when i debug the code.
What can be the problem?
Full Event Code:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=#eName");
cmd.parameters.AddParametersWithValue("#eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
EDIT
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
refer this
http://www.codeproject.com/Articles/37207/Editable-Gridview-with-Textbox-CheckBox-Radio-Butt
also put your code for Edit command. it might be RowEditing or RowCommand
I am creating a web page that contains one Dropdownlist and Gridview.
Query is Dropdownlist will contains SQL Server database table list. When I select a table name from dropdownlist the Gridview needs to show entire table data and able to perform edit, update, delete, cancel action.
When I click edit Gridview need to show update and cancel buttons and it update should update dropdownlist table and also delete.
My code looks this:
Html page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataGridView_Sample._Default" %>
<!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>Untitled Page</title>
<style type="text/css">
.style1
{
font-weight: bold;
text-decoration: underline;
font-size: x-large;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h5 class="style1">
Data Grid View Sample</h5>
</div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="-- Select --" Value=""></asp:ListItem>
<asp:ListItem Text="Emp" Value="Emp"></asp:ListItem>
<asp:ListItem Text="Dept" Value="Dept"></asp:ListItem>
</asp:DropDownList>
<br />
<br />
<b>Grid View:</b>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" Height="181px"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
Width="518px">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
<EmptyDataTemplate>
</EmptyDataTemplate>
</asp:GridView>
</form>
</body>
</html>
.aspx page code:
namespace DataGridView_Sample
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=SHINY-PC\\SQLEXPRESS;Initial Catalog=NRK;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
con.Open();
cmd = new SqlCommand("Select name from sys.tables order by name", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select--", "--Select--"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex != 0)
{
cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.EditIndex = Convert.ToInt16(e.NewEditIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
}
}
Please any one can help.
Thanks in advance.
Given the above, I'd create a database table with two fields: tablename and columnname. There will be 4 rows with tablename = emp and each row will have a columnname = one of the columns from the emp table. Similarly, there will be 6 rows where tablename = dept and each row will have a columnname = one of the columns from the dept table. Then, in your GridView1_RowUpdating event, you can pull the names of the columns from the database based on the table that's been chosen in the DropDownList and update accordingly using whatever stored procedure you have in place for that table. In GridView1_RowCancelingEdit, you just need to do
GridView1.EditIndex = -1;
and rebind your data (you'll need a method for that) you're done.