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
}
}
Related
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"
I am stuck because when i update the edit page on button click event, my page navigates to the home page that contains the gridview but the gridview row is not updated and remains the same. And please advice me how i can edit a page on a button click event using session.
This is the manager aspx page:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" OnRowCommand="GridView1_RowCommand" >
<%-- <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" DataKeyNames="USERID" DataSourceID="SqlDataSource1">--%>
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="USERID" HeaderText="USERID" ReadOnly="True" SortExpression="USERID"/>
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="EMAIL" HeaderText="EMAIL" SortExpression="EMAIL" />
<asp:BoundField DataField="PASSWORD" HeaderText="PASSWORD" SortExpression="PASSWORD" />
<asp:TemplateField >
<ItemTemplate>
<%--<asp:LinkButton ID="LinkButton1" runat="server" CommandName="EditButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" >Edit</asp:LinkButton>--%>
<asp:Button ID="btnEdit" runat="server" Width="60" Text="Edit" CommandName="EditButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="DeleteButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%-- hiddenfield for session--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdid" Value='<%#Eval("USERID")%>' runat="server"></asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
Navigate to edit.aspx page on clicking of edit button:
namespace WebApplicationSystem
{
public partial class Edit : System.Web.UI.Page
{
int empno = 0;
protected void Page_Load(object sender, EventArgs e)
{
empno = Convert.ToInt32(Request.QueryString["USERID"].ToString());
if (!IsPostBack)
{
BindTextBoxvalues();
}
}
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
OracleConnection con = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand("select * from LOGIN where USERID=" + empno, con);
DataTable dt = new DataTable();
OracleDataAdapter Oda = new OracleDataAdapter(cmd);
Oda.Fill(dt);
txtid.Text = dt.Rows[0][0].ToString();
txtfname.Text = dt.Rows[0][1].ToString();
txtlname.Text = dt.Rows[0][2].ToString();
txtemail.Text = dt.Rows[0][3].ToString();
txtpassword.Text = dt.Rows[0][4].ToString();
}
protected void btnregistration_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
OracleConnection con = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand("UPDATELOGIN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
OracleParameter OP1 = cmd.Parameters.Add("USERID", OracleDbType.Varchar2);
OP1.Direction = ParameterDirection.Input;
OP1.Value = txtid;
OracleParameter OP2 = cmd.Parameters.Add("FIRSTNAME", OracleDbType.Varchar2);
OP2.Direction = ParameterDirection.Input;
OP2.Value = txtfname;
OracleParameter OP3 = cmd.Parameters.Add("LASTNAME", OracleDbType.Varchar2);
OP3.Direction = ParameterDirection.Input;
OP3.Value = txtlname;
OracleParameter OP4 = cmd.Parameters.Add("EMAIL", OracleDbType.Varchar2);
OP4.Direction = ParameterDirection.Input;
OP4.Value = txtemail;
OracleParameter OP5 = cmd.Parameters.Add("PASSWORD", OracleDbType.Varchar2);
OP5.Direction = ParameterDirection.Input;
OP5.Value = txtpassword;
cmd.ExecuteNonQuery();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
//Fill the DataTable
oda.Fill(dt);
con.Close();
Response.Redirect("~/Manager.aspx");
}
}
}
To update your GridView after each click, don't forget to redefine your data source:
GridView1.DataSource = //your DataTable
GridView1.DataBind();
I'm not sure that I understand what you want to do with the session manager, but you can access the session object by HttpSessionState.Session.
Whenever I delete a row from the gridview which I select to delete, the row above to the selected row gets deleted. Dont know why. Please see my code for deleting.
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="10" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound" OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id">
<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>
</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" CommandName="Delete" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandArgument='<%# Eval("Id") %>' />
</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>
Code behind for your ref:-
protected void grdPostData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Post WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrposts.aspx';", true);
grdPostData.DataBind();
}
else
{
Response.Write("Some error");
}
}
Please let me know where I am going wrong. I tried debugging the code and the Id was taking 0.
Gridview bindinf Code:-
public void BindGrid()
{
string strQuery = "Select Id, title, description, Active from tbl_Post Order by ID desc";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
grdPostData.DataSource = dt;
grdPostData.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
try
{
conn.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
sda.Dispose();
conn.Dispose();
}
}
Updated Solution. Completely Working. I am Creating those textboxes in DataBound and theirs a if condition that checks whether Gridview is Empty or Not.
If Gridview is empty then HeaderRow wont be created so that Gridview and Page is able to display else HeaderRow will be Displayed.
Hope this Works for You.
aspx:-
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true"
CodeFile="csrposts.aspx.cs" Inherits="CSRProject.csrposts" %>
<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" OnDataBound="grdPostPageData_DataBound"
OnRowDataBound="grdPostData_RowDataBound" DataKeyNames="Id" OnRowDeleting="grdPostData_RowDeleting"
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:LinkButton ID="lbltbDelete" runat="server" OnClick="lbltbDelete_Click" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this record?')"
CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" CommandName="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>
<EmptyDataTemplate>
No Result Found
</EmptyDataTemplate>
</asp:GridView>
Aspx.cs
protected void grdPostPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
if (grdPostData.Rows.Count > 0)
{
grdPostData.HeaderRow.Parent.Controls.AddAt(0, row);
}
else
{
}
}
protected void grdPostData_RowDataBound(object sender, GridViewRowEventArgs e)
{
/*
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdPostData.HeaderRow.Parent.Controls.AddAt(-1, row);
// e.Row.Parent.Controls.AddAt(1, row);
}
*/
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from tbl_PostCategory ", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList DropDownList1 =
(DropDownList)e.Row.FindControl("ddlPostCategory");
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "cat_title";
DropDownList1.DataValueField = "cat_title";
DropDownList1.DataBind();
}
}
}
Row Deleting Code is Same.
Your code looks good. Hope its not a problem from database. Try this
Add this to Gridview
OnRowCommand="GridView_RowCommand"
CodeBehing:-
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Delete")
{
// Get the value of command argument
int Id= convert.ToInt32(e.CommandArgument);
// Do whatever operation you want.
}
}
Alternatively:-
Add onclick event on your imagebutton of delete and try this
protected void ImageButton_Click(object sender, EventArgs e)
{
ImageButton btn = sender as ImageButton;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int id =Convert.ToInt32((gRow.FindControl("lblId") as Label).Text);
}
Update:-
Change your itemtemplate to this
<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>
So Fetched Id will be visible next to dropdownlist. Make sure its displaying correct value
I'm working with Outward Challan Detail, in which I need to show the results on a form by a gridview.
My problem is that I don't know how to assign values to textbox existing in the gridview.
How could I assign values in the textbox inside my templates fields that are in my gridview by using dataReader or DataSet?
Here is my aspx
<div id="OutDCItemDetails" runat="server" style="overflow:auto">
<asp:Panel ID="PanelOutDCItemDetails" runat="server">
<asp:GridView ID="gvOutDCItemDetails" runat="server" AllowPaging="True"
PageSize="6" AutoGenerateColumns="False"
onrowdatabound="gvOutDCItemDetails_RowDataBound"
onrowcommand="gvOutDCItemDetails_RowCommand"
onselectedindexchanged="gvOutDCItemDetails_SelectedIndexChanged"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3" CellSpacing="1" GridLines="None" DataKeyNames="Item_Id" >
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField HeaderText="Item Id" DataField="Item_Id" />
<asp:BoundField HeaderText="Item Name" DataField="IName" />
<asp:BoundField HeaderText="Net Quantity" DataField="I_Quantity" />
<asp:BoundField DataField="Remaining_Qty" HeaderText="Remaining Quantity" />
<asp:TemplateField HeaderText="Process">
<ItemTemplate>
<asp:DropDownList ID="ddrProcess" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dispatch Quantity">
<ItemTemplate>
<asp:TextBox ID="txtDispatchQuantity" runat="server" AutoPostBack="true" OnTextChanged="TextChanged_txtDispatchQuantity"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remaining Quantity">
<ItemTemplate>
<asp:TextBox ID="txtRamainingQuantity" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="txtRate" runat="server" AutoPostBack="true" OnTextChanged="txtRate_TextChanged"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text="Status"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
Here is my C# code
protected void gvOutDC_SelectedIndexChanged1(object sender, EventArgs e)
{
if (gvOutDC.SelectedIndex >= 0)
{
btnsave.Enabled = false;
btnInword.Visible = false;
OutDC.Visible = true;
OutDCItemDetails.Visible = true;
View.Visible = false;
InwordDetails.Visible = false;
txtOutId.Visible = true;
txtoutCode.Enabled = false;
btn.Visible = true;
txtcustcode.Enabled = false;
btnsave.Enabled = true;
txtOutId.Text = gvOutDC.SelectedDataKey[0].ToString();
txtoutCode.Text = gvOutDC.SelectedRow.Cells[2].Text.ToString();
txtDate.Text =gvOutDC.SelectedRow.Cells[8].Text.ToString();
txtCustomerId.Text = gvOutDC.SelectedRow.Cells[5].Text.ToString();
txtcustcode.Text = gvOutDC.SelectedRow.Cells[7].Text.ToString();
txtCustomerName.Text = gvOutDC.SelectedRow.Cells[6].Text.ToString();
int inworditem = Convert.ToInt16(gvOutDC.SelectedRow.Cells[3].Text.ToString());
SqlCommand cmd = new SqlCommand("sp_getOutDCmaterialDetail",con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#outDCid", txtOutId.Text);
cmd.Parameters.AddWithValue("#inwordItem", inworditem);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
//.Text = ds.Tables[0].Rows[0][0].ToString();
con1.Open();
//SqlDataReader dr=cmd.ExecuteReader();
//if (dr.HasRows)
//{
// while (dr.Read())
// {
// }
//}
gvOutDCItemDetails.DataSource = ds;
gvOutDCItemDetails.DataBind();
OutDCItemDetails.Visible = true;
}
}
protected void gvOutDCItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if ((e.Row.RowState & DataControlRowState.Edit) > 0)
//{
DropDownList ddList = (DropDownList)e.Row.FindControl("ddrProcess");
//bind dropdownlist
SqlCommand cmd = new SqlCommand("sp_getProcess", con1);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
//DataTable dt = con1.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "PName";
ddList.DataValueField = "Process_Id";
ddList.DataBind();
ddList.Items.Insert(0,new ListItem("--SELECT--","0"));
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
txtDispatchQuantity.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtRamainingQuantity = (TextBox)e.Row.FindControl("txtRamainingQuantity");
txtRamainingQuantity.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtRate = (TextBox)e.Row.FindControl("txtRate");
txtRate.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtAmount = (TextBox)e.Row.FindControl("txtAmount");
txtAmount.Text = ds.Tables[0].Rows[0][3].ToString();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
// Label lblTotalPrice = (Label)e.Row.FindControl("Total_Amount");
//lblTotalPrice.Text = total.ToString();
// txttotalAmount.Text = Total.ToString();
}
}
You should directly bind the DataTable Column to TextBox inside the TemplateField like...
<asp:TextBox ID="txtDispatchQuantity" runat="server" Text='<%# Eval("ColumnNameInDataSetTable") %>' />
This directly binds the values to TextBoxes. You can do this for all other TextBoxes.
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
var dataRow = (DataRowView)e.Row.DataItem;
var Dispatch_Qty = "Dispatch_Qty";
var check = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(Dispatch_Qty, StringComparison.InvariantCultureIgnoreCase));
if (check)
{
// Property available
txtDispatchQuantity.Text =ds1.Tables[0].Rows[0][7].ToString();
}
protected void gvOutDCItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if ((e.Row.RowState & DataControlRowState.Edit) > 0)
//{
DropDownList ddList = (DropDownList)e.Row.FindControl("ddrProcess");
//bind dropdownlist
SqlCommand cmd = new SqlCommand("sp_getProcess", con1);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
//DataTable dt = con1.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "PName";
ddList.DataValueField = "Process_Id";
ddList.DataBind();
ddList.Items.Insert(0,new ListItem("--SELECT--","0"));
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
var dataRow = (DataRowView)e.Row.DataItem;
var Dispatch_Qty = "Dispatch_Qty";
var check = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(Dispatch_Qty, StringComparison.InvariantCultureIgnoreCase));
if (check)
{
// Property available
txtDispatchQuantity.Text =ds1.Tables[0].Rows[0][7].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
// Label lblTotalPrice = (Label)e.Row.FindControl("Total_Amount");
//lblTotalPrice.Text = total.ToString();
// txttotalAmount.Text = Total.ToString();
}
}
A short way with Simple and Inner Select, For use in ASPX code with no Code Behind:
....
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("COrder") %>' />
</td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("CText") %>' />
</td>
<td>
Delete
</td>
</tr>
</ItemTemplate>
....
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [RId],[CId],[COrder],[CText]=(SELECT [Title] from [Categories] where [ID]=[HomeProduct].[CId]) FROM [HomeProduct] ORDER BY [COrder] DESC"></asp:SqlDataSource>
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.