How do I get data of clicked button row of Grid View? - c#

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
}
}

Related

How can i transfer my gridview data to another aspx page?

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();

2 drop down list and calendar to display gridview in C#

I have simple booking ticketing system for my school project and am using windows form in asp.net. i have simple search where the person can input bickup, drop off and date. am using drop down list FOR bickup and dropoff and date normal calendar attached to text box. but i can't populate the gridview e.g bus rides available from one position to another in specific dates , like from A to B in 24 of August. my date i stored as date others Nvarchar. i can bind the drop down list but the search button shows nothing.
below is my front code and back-end code. please i need help am new to c# and coding in general.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tbdates" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</div>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped">
<Columns>
<asp:BoundField DataField="BusNo" HeaderText="Bus Number" />
<asp:BoundField DataField="date" HeaderText="Date" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:BoundField DataField="Bickup" HeaderText="Bick Up" />
<asp:BoundField DataField="DropOff" HeaderText="Drop Off" />
<asp:BoundField DataField="Fare" HeaderText="Fare" />
</Columns>
<HeaderStyle BackColor="#33CCFF" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
</form>
public partial class DriverDisplay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill_DropDownList1();
fill_DropDownList2();
}
}
private void fill_DropDownList1()
{
try
{
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString);
string sql = "SELECT * FROM Ticket";
SqlCommand cmd = new SqlCommand(sql, con2);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Bickup";
DropDownList1.DataValueField = "Bickup";
DropDownList1.DataBind();
}
catch (Exception)
{
}
}
private void fill_DropDownList2()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString);
string sql = "SELECT * FROM Ticket";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "Dropoff";
DropDownList2.DataValueField = "DropOff";
DropDownList2.DataBind();
}
catch (Exception)
{
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
tbdates.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
//DateTime date = Convert.ToDateTime(tbdates.Text);
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ToString());
sqlcon.Open();
string query = "select * from Ticket where date = #Date";
SqlCommand cmd = new SqlCommand(query, sqlcon);
SqlParameter date = cmd.Parameters.Add("#Date", SqlDbType.DateTime);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
sqlcon.Close();
}
}
}
there are a few mistakes in your code, i recommend you to read about CRUD Operations using ADO.Net and C# in ASP.Net, how to use SqlConnection and SqlCommand types. When you work with asp.net web forms you can use SqlDataSource control to provide data for your controls.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tbdates" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Bickup" DataValueField="Bickup">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource1" DataTextField="DropOff" DataValueField="Dropoff">
</asp:DropDownList>
</div>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="BusNo" HeaderText="Bus Number" />
<asp:BoundField DataField="date" HeaderText="Date" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:BoundField DataField="Bickup" HeaderText="Bick Up" />
<asp:BoundField DataField="DropOff" HeaderText="Drop Off" />
<asp:BoundField DataField="Fare" HeaderText="Fare" />
</Columns>
<HeaderStyle BackColor="#33CCFF" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabase1ConnectionString %>"
SelectCommand="SELECT [BusNo], [date], [time], [Bickup], [DropOff], [Fare] FROM [Ticket]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabase1ConnectionString %>" SelectCommand="SELECT [BusNo], [date], [time], [Bickup], [DropOff], [Fare] FROM [Ticket] WHERE ([date] = #date)">
<SelectParameters>
<asp:CookieParameter CookieName="date" DbType="Date" Name="date" />
</SelectParameters>
</asp:SqlDataSource>
this is yours DriverDisplay :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataBind();
DropDownList2.DataBind();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
tbdates.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Request.Cookies["date"] == null)
{
Request.Cookies.Add(new HttpCookie("date"));
}
Request.Cookies["date"].Value = tbdates.Text;
}

Javascript confirmation Box not appear on delete in gridview

When click on delete link-button in gridview, Confirmation Box not appeared. I write this code but I don't know why it's not working...
<asp:GridView ID="gvwAuctionExport" runat="server" AutoGenerateColumns="false" OnRowCommand="gvwAuctionExport_RowCommand" OnRowDataBound="gvwAuctionExport_RowDataBound" OnRowDeleting="gvwAuctionExport_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="btn-group btn-group-xs" id="bgroup">
<asp:LinkButton ID="lnkInspectionDelete" runat="server" Text="Delete" CssClass="btn btn-danger" CommandArgument='<%# Eval("inspection_id") %>' CommandName="Delete"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="address" HeaderText="Address" />
<asp:BoundField DataField="city" HeaderText="City" />
<asp:BoundField DataField="state" HeaderText="State" />
</Columns>
</asp:GridView>
protected void gvwAuctionExport_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int InspectionID = Convert.ToInt32(e.CommandArgument);
string status = string.Empty;
status = DACls.DeleteInspectionByID(InspectionID);
}
}
protected void gvwAuctionExport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("lnkInspectionDelete");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record");
}
}
protected void gvwAuctionExport_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bindGridView();
}
public void bindGridView(){
DataSet DS = new DataSet();
SqlConnection DBCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
SqlCommand Cmd = new SqlCommand("USP_Inspection_Export", DBCon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(this.DS);
DataTable dt = DS.Tables[0];
this.gvwAuctionExport.DataSource = dt;
this.gvwAuctionExport.DataBind();
}
When I click on delete button and check from debugger it is not going to GridView RowDataBound function scope. I don't know what happening here?

Gridview popout window to edit when clicked on a column

I have a gridview. I need to include a hyperlink to one of the columns so when the user clicks the link a popout should come with option to Edit and save. After the save the gridview should automatically get refreshed.
Following is my Gridview Code:
<asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit"
onrowediting="EmployeeGridView_RowEditing" onrowdeleting="EmployeeGridView_RowDeleting"
onrowupdating="EmployeeGridView_RowUpdating" Width="395px"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="EmployeeGridView_RowDataBound" AllowPaging="True"
onpageindexchanging="EmployeeGridView_PageIndexChanging1" PageSize="5">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText = "Action">
<ItemTemplate>
<asp:CheckBox ID = "chkDelete" runat = "server" AutoPostBack="True"
oncheckedchanged="chkDelete_CheckedChanged" />
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sr.No">
<ItemTemplate>
<asp:Label ID = "lblID" runat = "server" Text = '<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID = "lblEmpName" runat = "server" Text = '<%# Eval("Emp_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experience">
<ItemTemplate>
<asp:Label ID = "lblEmpExp" runat = "server" Text = '<%# Eval("Emp_exp") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID = "lblEmpAddress" runat = "server" Text = '<%# Eval("Emp_address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" ButtonType ="Button"
HeaderText="Edit" ControlStyle-BackColor= "#15524A" >
<ControlStyle BackColor="#15524A"></ControlStyle>
</asp:CommandField>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" HeaderText="Delete" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
The code behind is :
public partial class _Default : System.Web.UI.Page
{
SqlConnection connstr = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
Session["sortBy"] = e.SortExpression;
FillGrid();
}
protected void Page_Load(object sender, EventArgs e)
{
Session["sortBy"] = null;
if (!Page.IsPostBack)
{
FillGrid();
BindGrid();
}
}
public void FillGrid()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
DataTable dt = new DataTable();//object of data table that uses to conatin whole data
dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
EmployeeGridView.DataSource = dt;
EmployeeGridView.DataBind();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EmployeeGridView.EditIndex = -1;
FillGrid();
}
protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
EmployeeGridView.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void EmployeeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("EmployeeUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.Parameters.AddWithValue("#emp_name ", name);
cmd.Parameters.AddWithValue("#emp_exp ", experience);
cmd.Parameters.AddWithValue("#emp_address ", address);
cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
EmployeeGridView.EditIndex = -1;// no row in edit mode
FillGrid();
}
protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.ExecuteNonQuery();
FillGrid();
}
protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
EmployeeGridView.PageIndex = e.NewPageIndex;
FillGrid();
}
protected void buttonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
var lblID = row.FindControl("lblID") as Label;
Response.Write(lblID.Text + "<br>");
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand("Delete from tbl_employee where Emp_id=#emp_id", conn);
// comm.CommandType = CommandType.StoredProcedure;
conn.Open();
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.ExecuteNonQuery();
conn.Close();
}
}
FillGrid();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var lblID = row.FindControl("lblID") as Label;
var lblEmpName = row.FindControl("lblEmpName") as Label;
var lblEmpExp = row.FindControl("lblEmpExp") as Label;
var lblEmpAddress = row.FindControl("lblEmpAddress") as Label;
//Response.Write(lblFirstName.Text + "<br>");
SqlCommand comm = new SqlCommand("EmployeeUpdate", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.Parameters.AddWithValue("#emp_name", EmpName.Text);
comm.Parameters.AddWithValue("#emp_exp", EmpExp.Text);
comm.Parameters.AddWithValue("#Emp_address", EmpAddress.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
EmpName.Visible = false;
EmpExp.Visible = false;
EmpAddress.Visible = false;
}
}
FillGrid();
}
}
For the column Name I need to make a hyperlink and when clicked the popout should come to edit and view data
Not sure I fully understand what do you need but you can check out how modal popup works in MS AJAX toolkit and try to emulate sample code that comes with the download.

How to bind a GridView from code behind and update the same

I check many sites and referred many codes before I could post a questions here. I am facing lot of confusions seeing them. Here is my problem.
I have a GridView and I have bound it from code behind as :
public void BindData()
{
SqlCommand comd = new SqlCommand("SELECT * FROM " + Label2.Text + "", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
And my asp.net for the same looks like :
<asp:GridView ID="GridView1" runat="server" ForeColor="#333333"
AutoGenerateEditButton="True" DataKeyNames="Locations"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Locations">
<ItemTemplate>
<asp:Label ID="LblLocations" runat="server" Text='<%#Eval("Locations") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lamp_Profile1">
<ItemTemplate>
<asp:Label ID="LblLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fan_Profile1">
<ItemTemplate>
<asp:Label ID="LblFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AC_Profile1">
<ItemTemplate>
<asp:Label ID="LblAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
And I have written my GridView1_RowCancelingEdit like:
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
And my GridView1_RowEditing looks like:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
And my GridView1_RowUpdating looks like:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = e.RowIndex;
Label Locations = GridView1.Rows[e.RowIndex].FindControl("LblLocations") as Label;
//ViewState["Locations_Instance"] = Locations.Text;
Label Lamp_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblLamp_Profile1") as Label;
Label Fan_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblFan_Profile1") as Label;
Label AC_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblAC_Profile1") as Label;
string query = "UPDATE " + Label3.Text + " SET Lamp_Profile1 ='" + Lamp_Profile1 + "', Fan_Profile1 ='" + Fan_Profile1 + "', AC_Profile1 ='" + AC_Profile1 + "' WHERE Locations = '" + Locations + "'";
com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
//lbldisplay.Text = "Updated Successfully";
}
From this I am getting what ever row I am binding using template field as well as database columns in my GridView and Once I click on Edit in the GridView, the whole GridView disappears.
Please help me.
You can find the textbox that is generated on edit event in the RowUpdating event below and assign it to a string variable.
Then have a seperate function to update the values entered and finally call your BindGrid() function which again binds the gridview..
Note: I'm using stored procedure to update my DB table.
protected void grdKeywords_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grdKeywords.Rows[e.RowIndex];
TextBox txtKeyword = row.FindControl("txtGridKeyword") as TextBox;
string keyword = string.Empty;
keyword = txtKeyword.Text;
UpdateKeyword(keyword.ToLower());
}
public int UpdateKeyword(string strKeyword)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
SqlCommand cmdUpdateKeyword = BuildCommand(conn, "proc_UpdateKeyword");
cmdUpdateKeyword.Parameters.AddWithValue("#Keyword", strKeyword);
conn.Open();
int i = Convert.ToInt32(cmdUpdateKeyword.ExecuteScalar());
conn.Close();
BindGrid();
}
To manually specify columns for the gridview you have to set AutoGenerateColumns="false". Now you can specify the columns that you want in your GridView. You can use both "BoundFields" & "TemplateFields" now. As shown below.
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="column1" HeaderText="Column1" SortExpression="" />
<asp:BoundField DataField="column2" HeaderText="Column2" SortExpression="" />
<asp:TemplateField SortExpression="points">
<HeaderTemplate>HELLO</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("hello") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now you can use:
GridView.RowDataBound Event to bind data to the data row.
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label Label1= ((Label)e.Row.FindControl("Label1"));
Label1.Text = "YOURDATA";
}
}
if you call BindData in page load then do that:
if (!IsPostBack)
BindData();
That might solve your problem...
Cheers
public int UpdateKeyword(string strKeyword)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
SqlCommand cmdUpdateKeyword = BuildCommand(conn, "proc_UpdateKeyword");
cmdUpdateKeyword.Parameters.AddWithValue("#Keyword", strKeyword);
conn.Open();
int i = Convert.ToInt32(cmdUpdateKeyword.ExecuteScalar());
conn.Close();
BindGrid();
}
Make sure you have EnableViewState="true" set in your GridView. It solved disapperance-issue in my case.
try this ..
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = e.RowIndex;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox PrStyle = (TextBox)row.FindControl("PrStyle");
TextBox PrID = (TextBox)row.FindControl("PrID");
GridView1.EditIndex = -1;
SqlCommand cmd = new SqlCommand("Update dt Set PrStyle='" + PrStyle + "',PrID='" + PrID + "'");
}

Categories

Resources