Gridview popout window to edit when clicked on a column - c#

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.

Related

How to download a file from a specific row in GridView

I need some assistance with downloading a file in a specific row in my GridView.
This is my code for the the GridView markup:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="id"
CssClass="mydatagrid"
Width="550px"
BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None"
BorderWidth="1px"
CellPadding="3"
CellSpacing="2"
AllowSorting="true">
<Columns>
<asp:BoundField DataField="filename" HeaderText="Name" />
<asp:BoundField DataField="datestamp" HeaderText="Date" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
Text="Download"
ControlStyle-CssClass="btn btn-success"
CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" width="250px" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
And then for downloading the file I have:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["filecontent"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
So what happens now is when I click on the download it always download the first row's file instead of the row I clicked on to download.
I know I need to specify on which row I have clicked in order to download the file, but not sure on how to accomplish it?
Thanks
It is because of this line
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You then need to change from onclick to a grid command:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server"Text="Download"
ControlStyle-CssClass="btn btn-success" CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
</ItemTemplate>
</asp:TemplateField>
And in your code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["id"];
// you can run your query here
}
}
In your case:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
var val = this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = val;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
You need to also add the onrowcommand="ContactsGridView_RowCommand" to your Gridview
<asp:GridView ID="GridView1" runat="server" onrowcommand="ContactsGridView_RowCommand"

Gridview row is not getting updated --

I have a Gridview on which I have Edit option for editing the Row. I have written the code for Edit and Update but it is not getting updated and the row gets blank. I debugged the code and didn't got to know what was the exact problem. Please see the code for your ref and let me know what is the exact issue:-
Gridview aspx code:
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False"
AllowPaging="true" PageSize="4" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound"
OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id" OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Also see the CS code:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
// DropDownList ddlPostlistcategory = ((DropDownList)(row.Cells[0].Controls[0]));
TextBox txtPostTitle = ((TextBox)(row.Cells[0].Controls[0]));
TextBox txtPostdesc = ((TextBox)(row.Cells[1].Controls[0]));
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
grdPostData.DataBind();
}
}
protected void grdPostData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdPostData.EditIndex = -1;
BindGrid();
}
Edited part of the code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory");
//TextBox title = ((TextBox)(row.Cells[0].Controls[0]));
//TextBox description = ((TextBox)(row.Cells[1].Controls[0]));
TextBox title = (TextBox)row.FindControl("txtPostTitle");
TextBox description = (TextBox)row.FindControl("txtPostdesc");
DropDownList ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_post SET title=#title,description=#description,active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
grdPostData.EditIndex = -1;
grdPostData.DataBind();
}
}
Code Is perfect just small mistake.
Change
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
To
TextBox ddlActive = ((TextBox)(row.Cells[3].Controls[0]));
You want to set value of Active which is 3rd control not 2nd.
If Your control is in TemplateField then you have find control from row
For DropDownList You need to try something like this:
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
Following Line will generate error
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
You need to find this control ddlActiveInactive from grid which you are missing
Don't Use AddWithValue it gives Unexpected Results Sometimes
SOURCE
EDIT:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
string PostTitle = row.Cells[0].Text;
string Postdesc = row.Cells[1].Text;
string Active = row.Cells[2].Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.Add("#Id",SqlDbType.Int).Value=Id;
cmd.Parameters.Add("#title",SqlDbType.Varchar,100).Value=PostTitle ;
cmd.Parameters.Add("#description",SqlDbType.Varchar,200).Value= Postdesc ;
cmd.Parameters.Add("#Active",SqlDbType.Int).Value=Convert.ToInt32(Active);
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
//GET GDATA FROM DATABASE AND BIND TO GRID VIEW
}
}

Approve / reject through dropdownlist

Previously I tried to approve / reject through button and try to code it..
This is code when I add buttons of approve / reject
protected void GrdFileApprove_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "_Approve")
{
//using (SqlConnection con = DataAccess.GetConnected())
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
Button Prove_Button = (Button)row.FindControl("BtnApprove");
SqlCommand cmd = new SqlCommand("approveee", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
//con.Execute("approve", new { UserID, DocID, ApproveID });
cmd.Parameters.Add(new SqlParameter("#UserID", UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Not Approve";
}
finally
{
con.Close();
}
}
}
else if (e.CommandName == "_Reject")
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
LinkButton Prove_Button = (LinkButton)row.FindControl("Button1");
SqlCommand cmd = new SqlCommand("sprejectapprove", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserID",UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Rejct";
}
finally
{
con.Close();
}
}
}
}
and this grdiview when I add dropdown..
<asp:GridView ID="GrdFileApprove" runat="server" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AutoGenerateColumns="False"
onrowcommand="GrdFileApprove_RowCommand" OnRowDataBound="OnRowDataBound" >
<Columns>
<asp:TemplateField HeaderText="S no">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
<asp:HiddenField runat="server" ID="HdnFileID" Value='<%# Eval("DocID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocID" HeaderText="DocumentID" />
<asp:BoundField DataField="DocName" HeaderText="DocName" />
<asp:BoundField DataField="Uploadfile" HeaderText="File Name" />
<asp:BoundField DataField="DocType" HeaderText="Document" />
<asp:BoundField DataField="DepType" HeaderText="Department" />
<%-- <asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
--%> <asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="White" ForeColor="#333333" />
<FooterStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Now I want to code of dropdown.. when I click on approve/reject it can be approve/reject
how to code it and how to approve or reject through dropdown..
I have changed markup for DropDownList4:
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown" AutoPostBack="true" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged">
<asp:ListItem Text="Approve" Value="Approve"></asp:ListItem>
<asp:ListItem Text="Reject" Value="Reject"></asp:ListItem>
</asp:DropDownList>
And in the code:
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
if (ddl.SelectedValue == "Approved")
{
//Code to approve
}
else if (ddl.SelectedValue == "Reject")
{
//Code to reject
}
}

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 + "'");
}

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

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

Categories

Resources