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>
Related
Failed to load resource: the server responded with a status of 404 ()
System.Byte[]:1
This error is coming on inspecting it
protected void AllData()
{
if (Session["AddProduct"].ToString() == "true")
{
Session["AddProduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("ImageID");
dt.Columns.Add("ImageName");
dt.Columns.Add("ImageFile");
dt.Columns.Add("Price");
if (Request.QueryString["Id"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
string cont = #"";
SqlConnection sqlcon = new SqlConnection(cont);
SqlCommand cmd = new SqlCommand();
string query = "select * from tblclothes where ImageID=" + Request.QueryString["Id"];
cmd.CommandText = query;
cmd.Connection = sqlcon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["ImageID"] = ds.Tables[0].Rows[0]["ImageID"].ToString();
dr["ImageName"] = ds.Tables[0].Rows[0]["ImageName"].ToString();
dr["ImageFile"] = ds.Tables[0].Rows[0]["ImageFile"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
gvproducts.DataSource = dt;
gvproducts.DataBind();
Session["buyitems"] = dt;
}
this is the code
protected static string ReturnEncodedBase64UTF8(object rawImg)
{
string img = "data:image/jpg;base64,{0}"; //change image type if need be
string toEncodeAsBytes = rawImg.ToString();
string returnValue = System.Convert.ToString(toEncodeAsBytes);
return String.Format(img, returnValue);
}
<asp:GridView ID="gvproducts" OnRowDataBound="gvproducts_RowDataBound" ShowFooter="true" HeaderStyle-BackColor="Blue"
HeaderStyle-ForeColor="White" OnRowDeleting="gvproducts_RowDeleting" runat="server" AutoGenerateColumns="false"
EmptyDataText="No Data Available" FooterStyle-Font-Bold="true" Width="400px">
<Columns>
<%--<asp:BoundField DataField="S.No" HeaderText="S.No" />--%>
<asp:BoundField DataField="ImageId" HeaderText="Image Id" />
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<%--<asp:ImageField DataImageUrlField="ImageFile" HeaderText="Image"></asp:ImageField>--%>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<%--<img src='../Images/ <%# Eval("ImageFile") %>' id="img" runat="server" />--%>
<asp:Image ID="img" runat="server" ImageUrl='<%# "data:Image/png;base64," + Eval("ImageFile") %>' />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="OriginalFormat" HeaderText="Format" />--%>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text="Total Price"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
Regarding you case, you need to do the following:
When getting the DataRow, you need to cast it to Byte[] and convert it to a Base64 string like this:
dr["ImageFile"] = Convert.ToBase64String((Byte[])ds.Tables[0].Rows[0]["ImageFile"]);
Once you have the Base64 string, then you can apply it to your control like this:
<img src='data:image/jpg;base64, <%# Eval("ImageFile")%>' />
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 am sorting my date with my sql query and I get a proper result.
But as I apply
gridview.UseAccessibleHeader = true;
gridview.HeaderRow.TableSection = TableRowSection.TableHeader;
to my gridview. The sorted data gets unsorted.
this.gridviewname.MasterTemplate.EnableSorting = true;
this.RadGridView1.MasterTemplate.EnableSorting = True
SortDescriptor descriptor = new SortDescriptor();
descriptor.PropertyName = "Yourcolumnname";
descriptor.Direction = ListSortDirection.Ascending;
this.gridviewname.MasterTemplate.SortDescriptors.Add(descriptor);
descriptorcolumnname As New SortDescriptor()
descriptorShipName.PropertyName = "columnname"
descriptorShipName.Direction = ListSortDirection.Ascending
try this
Try this code which is working fine for me.
-- C# Code here---
<form id="form1" runat="server">
<div>
<h1>Gridview Property of Sorting</h1>
<br />
<asp:GridView ID="gdviewevent" runat="server" AutoGenerateColumns="false" OnSorting="gdviewevent_Sorting" AllowSorting="true">
<HeaderStyle BackColor="YellowGreen" Font-Bold="True" Font-Names="cambria" ForeColor="Black" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:TemplateField HeaderText="Sr No.">
<ItemTemplate>
<span><%#Container.DataItemIndex+1 %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="India Value" SortExpression="IndiaVal">
<ItemTemplate>
<asp:Label ID="lblindiavalue" runat="server" Text='<%#Eval("Column1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date" SortExpression="Registereddate">
<ItemTemplate>
<asp:Label id="lblcreateddate" runat="server" Text='<%#Eval("Registereddate", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
-- Page behind Code ---
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridView();
}
}
protected void FillGridView()
{
string query = "Select Column1, Registereddate from tablename";
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gdviewevent.DataSource = dt;
gdviewevent.DataBind();
ViewState["dirState"] = dt;
ViewState["sortdr"] = "Asc";
}
}
protected void gdviewevent_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
gdviewevent.DataSource = dtrslt;
gdviewevent.DataBind();
}
}
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
}
}
I have a GridView that is bound to a DataTable, and when you select edit, I can get the values to change. However, one field needs to be a dropdownlist and not a textbox. Here's the code I have so far.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
//dt.Rows[row.DataItemIndex]["Shipping Method"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
DropDownList cmbType = (DropDownList)griditems.Rows[e.RowIndex].FindControl("Shipping Method");
griditems.EditIndex = -1;
BindData();
}
}
When I uncomment the line for the shipping method to be a textbox, it does just as it says, a textbox, not a dropdownlist. I have tried changing it to a DropDownList with no luck.
In the aspx file:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing"
onrowupdating="griditems_RowUpdating" AllowPaging="True" onpageindexchanging="griditems_PageIndexChanging"
onrowcancelingedit="griditems_RowCancelingEdit" ViewStateMode="Enabled" Caption="Order Details"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
onrowdatabound="griditems_RowDataBound" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double" /></asp:GridView>
and when the table is generated:
public void CreateTable()
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
Try dis:
Default.aspx: (Best practise use Template Field in GridView)
<asp:GridView ID="gvshipping" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="gvshipping_RowCancelingEdit"
onrowdatabound="gvshipping_RowDataBound"
onrowediting="gvshipping_RowEditing" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Part">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("part") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" Text='<%# Bind("part") %>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quatity">
<ItemTemplate>
<asp:Label ID="lblqty" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtqty" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship to">
<ItemTemplate>
<asp:Label ID="lblshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post date">
<ItemTemplate>
<asp:Label ID="lblpostdate" runat="server" Text='<%# Bind("RequestedDate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpostdate" Text='<%# Bind("RequestedDate")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate>
<asp:Label ID="lblshipmethod" runat="server" Text='<%# Bind("ShippingMethod")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</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>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvBind();
}
}
public void gvBind()
{
DataTable dt = createTable();
Session["tb"] = dt;
gvshipping.DataSource = Session["tb"];
gvshipping.DataBind();
}
protected void gvshipping_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dpshipmethod = (DropDownList)e.Row.FindControl("DropDownList1");
//bind dropdownlist
DataTable dt = shipingmethodTable();
dpshipmethod.DataSource = dt;
dpshipmethod.DataTextField = "ShippingMethod";
dpshipmethod.DataValueField = "Id";
dpshipmethod.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
dpshipmethod.SelectedItem.Text = dr["ShippingMethod"].ToString();
}
}
}
protected void gvshipping_RowEditing(object sender, GridViewEditEventArgs e)
{
gvshipping.EditIndex = e.NewEditIndex;
vBind();
}
protected void gvshipping_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvshipping.EditIndex = -1;
gvBind();
}
public DataTable createTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Part", typeof(string));
dt.Columns.Add("Quantity", typeof(Int32));
dt.Columns.Add("ShipTo", typeof(string));
dt.Columns.Add("RequestedDate", typeof(string));
dt.Columns.Add("ShippingMethod", typeof(string));
string date= DateTime.Now.ToShortDateString();
DataRow row = dt.NewRow();
row["Part"] = "Anchor";
row["Quantity"] = "10";
row["ShipTo"] = "blah";
row["RequestedDate"] = date;
row["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row);
DataRow row1 = dt.NewRow();
row1["Part"] = "blade";
row1["Quantity"] = "88";
row1["ShipTo"] = "blah";
row1["RequestedDate"] = date;
row1["ShippingMethod"] = "Charge by quantity";
dt.Rows.Add(row1);
DataRow row2 = dt.NewRow();
row2["Part"] = "cabin";
row2["Quantity"] = "4";
row2["ShipTo"] = "blah";
row2["RequestedDate"] = date;
row2["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row2);
DataRow row3 = dt.NewRow();
row3["Part"] = "cockpit";
row3["Quantity"] = "11";
row3["ShipTo"] = "blah";
row3["RequestedDate"] = date;
row3["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row3);
DataRow row4 = dt.NewRow();
row4["Part"] = "jack";
row4["Quantity"] = "45";
row4["ShipTo"] = "blah";
row4["RequestedDate"] = date;
row4["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row4);
DataRow row5 = dt.NewRow();
row5["Part"] = "cabin";
row5["Quantity"] = "67";
row5["ShipTo"] = "blah";
row5["RequestedDate"] = date;
row5["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row5);
DataRow row6 = dt.NewRow();
row6["Part"] = "blade";
row6["Quantity"] = "4";
row6["ShipTo"] = "blah";
row6["RequestedDate"] = date;
row6["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row6);
return dt;
}
public DataTable shipingmethodTable()
{
DataTable dtshipingmethod = new DataTable();
dtshipingmethod.Columns.Add("Id", typeof(Int32));
dtshipingmethod.Columns.Add("ShippingMethod", typeof(string));
DataRow row = dtshipingmethod.NewRow();
row["Id"] = 1;
row["ShippingMethod"] = "Charge by subtotal";
dtshipingmethod.Rows.Add(row);
DataRow row1 = dtshipingmethod.NewRow();
row1["Id"] = 2;
row1["ShippingMethod"] = "Charge by weight";
dtshipingmethod.Rows.Add(row1);
DataRow row2 = dtshipingmethod.NewRow();
row2["Id"] = 3;
row2["ShippingMethod"] = "Charge by quantity";
dtshipingmethod.Rows.Add(row2);
return dtshipingmethod;
}
ScreenShot:
you can go ahead with the help of this:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)row.FindControl("DropdownList1")).SelectedItem;
EDIT:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)
(row.Cells[5].Controls[0])).SelectedItem.ToString();