AJAX asp Web Forms search in grid - c#

I found implementation of my problem on a side but i dont know why it isn't working. When i put some value into textbox it should do me a postback but it does not.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView2">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
And code behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE amount > 1000";
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE client_name Like '" + txt.Text + "%'"
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
http://www.infosearchshop.com/21-gridview-search-as-you-type-with-ajax

I would suggest to update the AsyncPostBackTrigger as follow to match the ID of the textbox = TextBox1 with the AutoPostBack reference but the control needs to be outside the UpdatePanel
<asp:AsyncPostBackTrigger ControlID ="TextBox1" EventName ="TextChanged" />
I would also suggest trying to use PostBackTrigger instead. This is mostly used for controls inside the UpdatePanel that makes a full post back
<asp:PostBackTrigger ControlID="TextBox1" />

TextBox 's id and GridView's ID don't match .
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="txt" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
private DataTable GetDataSource()
{
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("regon", typeof(string));
dt.Columns.Add("nip", typeof(string));
dt.Rows.Add("Name-1", "regon-1", "nip-1");
dt.Rows.Add("Name-2", "regon-1", "nip-1");
dt.Rows.Add("Name-3", "regon-1", "nip-1");
dt.Rows.Add("Name-4", "regon-1", "nip-1");
dt.Rows.Add("Name-5", "regon-1", "nip-1");
dt.Rows.Add("Name-6", "regon-1", "nip-1");
dt.Rows.Add("Name-7", "regon-1", "nip-1");
return dt;
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}

Related

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

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

CheckBox is not working when I am pressing the button

I am working with Asp.Net C# and want to take the id of the row with a checkbox from the GridView.
With the code above if is checked the only think i am getting with debug is:
chk: {Text = "" Checked = false}
What i am doing wrong and how i can fix this?
<!-- language: lang-css -->
protected void Page_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
if(!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
string user = Session["user"].ToString();
using (MySqlConnection con2 = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT RouteNo,sender FROM routedoc WHERE Recipient = #user ", con2);
adp.SelectCommand.Parameters.AddWithValue("?user", user);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sender";
DropDownList1.DataValueField = "RouteNo";
DropDownList1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Write(GridView1.SelectedRow.Cells[1].Text);
foreach(GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("box") as CheckBox ;
if (chk.Checked)
{
var id = row.FindControl("RouteNo") as Label;
Response.Write(id.Text);
}
}
}
routedoc.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="routedoc.aspx.cs" Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>page 2<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="136px" >
</asp:DropDownList>
</h1>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Recipient,DocHandle,Sender" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RouteNo" HeaderText="RouteNo" InsertVisible="False" SortExpression="RouteNo" />
<asp:BoundField DataField="Recipient" HeaderText="Recipient" ReadOnly="True" SortExpression="Recipient" />
<asp:BoundField DataField="DocHandle" HeaderText="DocHandle" ReadOnly="True" SortExpression="DocHandle" />
<asp:BoundField DataField="Sender" HeaderText="Sender" ReadOnly="True" SortExpression="Sender" />
<asp:BoundField DataField="TermNo" HeaderText="TermNo" SortExpression="TermNo" />
<asp:BoundField DataField="SentDate" HeaderText="SentDate" SortExpression="SentDate" />
<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate" />
<asp:BoundField DataField="SentTime" HeaderText="SentTime" SortExpression="SentTime" />
<asp:BoundField DataField="DueTime" HeaderText="DueTime" SortExpression="DueTime" />
<asp:BoundField DataField="Action" HeaderText="Action" SortExpression="Action" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="BUDate" HeaderText="BUDate" SortExpression="BUDate" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox ID="Box" runat="server"/>
</ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:imagingConnectionString %>" ProviderName="<%$ ConnectionStrings:imagingConnectionString.ProviderName %>" SelectCommand="SELECT * FROM routedoc "></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Height="43px" OnClick="Button1_Click" Text="DELETE" Width="109px" />
</form>
</body>
</html>
This is caused by the fact that you always bind your GridView1 with data,
even on post-back. This is causing that all check box-es remain unchecked.
Remove grid loading if you are in post-back, and it should work fine.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
BindDropDown();
}
}
If you, however, need to load grid even in post-back, I will tell you a fix for that.
Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// bind data
}
}
This is because, when you click a button, your page will be still refreshed, which means you will bind the same data to gridview again, resulting in unchecked checkboxes. You can check whether the page is loaded by a button click (Page.IsPostBack) or the page is loaded the first time (!Page.IsPostBack), and do your data binding accordingly.
Hope this makes sense!

asp.net gridview Sorting by date

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

Gridview Paging ASP.NET with Pager Panel outside Gridview

This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>

set values to TextBox in Item template of gridview

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>

Categories

Resources