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")%>' />
Related
I have a SQL Server table with filestream enabled. I am able to upload files here and update as well. How do I read these files into an .aspx web page? The files are .pdf files.
There are 2 files are associated with each row.
I am reading the row into a .aspx page and at the bottom I want the files to open up one below the other. This is for the user to print the row with the files.
I have checked out the code suggested by #dinglemeyer. I do want to conver my pdf to image. I am assuming there is a simple way:
<asp:GridView ID="gridview_f" runat="server" ShowHeaderWhenEmpty="false" PageSize="2" DataKeyNames="ID" DataSourceID="sql_files" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="selID" runat="server" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="selFname" runat="server" Text='<%# Bind("filename") %>' />
<br />
<asp:image ID="selFile" runat="server" ImageUrl='<%# "Handler.ashx?id="+Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// code behind for ginfing the grid as the parentId is extracted from other form values.
private void gridView_Data(string id)
{
sql_files.SelectCommand = "SELECT ID, filename from myFILESTABLE where PARENTID=" + id;
}
// Handler.ascx
public void ProcessRequest(HttpContext context)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["my_dbconn"].ConnectionString);
try
{
cmd = new SqlCommand("SELECT filecontent from myFILESTABLE WHERE ID=" + context.Request.QueryString["ID"], conn);
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
context.Response.ContentType = "content/pdf";
context.Response.BinaryWrite((byte[])sdr["filecontent"]);
}
sdr.Close();
}
finally
{
conn.Close();
}
My apologies for the delayed reply.From the link:http://weblogs.asp.net/aghausman/saving-and-retrieving-file-using-filestream-sql-server-2008 Here is my working code:
<asp:GridView ID="mygrid1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" DataSourceID="sql_file" OnRowCommand="gridview_f_RowCommand" GridLines="None" >
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%# Container.DataItemIndex + 1 %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachments" >
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("ID") %>' Visible="false" />
<asp:LinkButton ID="lLabel12" runat="server" Text='<%# Bind("myFileName") %>' CommandName="GetFile" CommandArgument='<%#Eval("ID") + "|" + Eval("myFileName") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
" >
The code behind:
protected void gridview_f_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="GetFile")
{
string[] ca = e.CommandArgument.ToString().Split('|');
SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);
objSqlCon.Open();
SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
SqlCommand objSqlCmd = new SqlCommand("spGet_getMyFile", objSqlCon, objSqlTran);
objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter objSqlParam1 = new SqlParameter("#ID", SqlDbType.VarChar);
objSqlParam1.Value = ca[0]; // e.CommandArgument;
objSqlCmd.Parameters.Add(objSqlParam1);
string path = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
path = sdr[0].ToString();
}
}
objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
byte[] buffer = new byte[(int)objSqlFileStream.Length];
objSqlFileStream.Read(buffer, 0, buffer.Length);
objSqlFileStream.Close();
objSqlTran.Commit();
Response.AddHeader("Content-disposition", "attachment; filename=" + ca[1]);
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
The Stored procedure SpGet_getMyfile is:
CREATE PROCEDURE [dbo].[spGet_getMyFile]
(
#id BIGINT
)
AS
SELECT filestreamColumn.PathName()
FROM dbo.TableThatHasTheFileStream
WHERE Id=#id
I am new in asp.net development
I have created a project its working fine but i want to select the Designation from drop down but want to store the id of the designation instead of the designation
Here is my Asp.net Code for my Project
protected void BindData()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from EmployeeDetails";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)GridView1.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)GridView1.FooterRow.FindControl("txtAddName");
DropDownList ddlDesignation = (DropDownList)GridView1.FooterRow.FindControl("ddlDesignation");
TextBox txtAddCity = (TextBox)GridView1.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)GridView1.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlDesignation = (DropDownList)e.Row.FindControl("ddlDesignation");
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from Designation";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
ddlDesignation.DataSource = ds.Tables[0];
ddlDesignation.DataTextField = "designation";
ddlDesignation.DataValueField = "id";
ddlDesignation.DataBind();
ddlDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
this.TextBox1.Text = ddlDesignation.SelectedItem.ToString();
conn.Close();
}
}
and also this is my aspx.cs code for project
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false" ShowFooter="true" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_OnRowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDesignation" runat="server" >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCity" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCountry" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD" Text="Add" Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to get value from SelectedValue property of dropdwon.
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedValue.ToString());
Did you try
var e = document.getElementById("ddlDesignation");
var strDesigId = e.options[e.selectedIndex].value;
document.getElementById("TextBox1").value = strDesigId;
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 in .aspx page that I want to hide columns based on aspx.cs BindData() method. I have tried using below code but not able to hide. I am using Asp.net with C#.
Below is my GridView with columns and I have also included the Button click code.
<GridView>
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id"
Visible="false" />
<asp:TemplateField HeaderText="RollNo" >
<ItemTemplate>
<%# Eval("st_rollno")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbsturollno" runat="Server"
Text='<%# Eval("st_rollno") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("st_name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbstuname" runat="Server"
Text='<%# Eval("st_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory">
<ItemTemplate>
<%# Eval("theory")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheory" runat="Server"
Text='<%# Eval("theory") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ttotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheorytotal" runat="Server"
Text='<%# Eval("ttotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lab" >
<ItemTemplate>
<%# Eval("lab")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblab" runat="Server"
Text='<%# Eval("lab") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ltotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblabtotal" runat="Server"
Text='<%# Eval("ltotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial" >
<ItemTemplate>
<%# Eval("tutorial")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorial" runat="Server"
Text='<%# Eval("tutorial") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("tutotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorialtotal" runat="Server"
Text='<%# Eval("tutotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
if (stype.Equals("L"))
{
query = "SELECT [id], [st_rollno], [st_name], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T"))
{
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[5].Visible = false;
GridView1.Columns[6].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T-L"))
{
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
else
{
query = "SELECT [id], [st_rollno], [st_name],[theory], [ttotal], [lab], [ltotal], [tutorial], [tutotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
com = new SqlCommand(query);
com.Parameters.Add("#branch_name", dept);
com.Parameters.Add("#scode", dpsubject.SelectedItem.Text.ToString());
com.Parameters.Add("#sem_no", Int32.Parse(dpsemno.SelectedItem.Text.ToString()));
com.Parameters.Add("#sess_no",Int32.Parse(dpsessional.SelectedItem.Text.ToString()));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.Connection = con;
con.Open();
sda.SelectCommand = com;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
protected void bsubmit_Click(object sender, EventArgs e)
{
this.BindData();
}
<asp:GridView runat="server" ID="GridView1"
AutoGenerateColumns="False" OnPreRender="GridView_PreRender">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var users = new List<User>
{
new User {FirstName = "John", LastName = "Doe"},
new User {FirstName = "Marry", LastName = "Newton"},
new User {FirstName = "Joe", LastName = "Black"}
};
GridView1.DataSource = users;
GridView1.DataBind();
}
}
protected void GridView_PreRender(object sender, EventArgs e)
{
foreach (DataControlField column in GridView1.Columns)
if (column.HeaderText == "FirstName")
column.Visible = false;
}
With the GrideView.DataBind() you're calling a PostBack that will undo any changed you've made to the front end. Try doing the work on the columns after the DataBind.