The code was working before and all i did was add a new textbox in the header template of the gridview.
So What is my code doing:
i have an image button on my gridview view when clicked i take the value of of the current row of the gridview and the value of cell 3 and set it equal to my textbox. Then based on that value i am making two details view visible using a modal popup extender, one detail view renders correctly but will not function unless it gets the value from textbox10.text as a parameter, another details view will not even show the details because the select query takes the textbox10.text as a parameter.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (!IsPostBack)
{
}
else
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1 = (GridViewRow)imgbtn.NamingContainer;
string workordernum = GridView1.Cells[3].Text;
TextBox10.Text = workordernum;
//TextBox10.Text = "1";
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}
}
when i put the above code in debug mode:
after debug completed:
When i set the textbox10.text = 1 and ran the application:
complete application with value 1:
.aspx code of the details view:
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="pnl2" PopupControlID="pnl2" BackgroundCssClass="modalBackground" DropShadow="False" X="30" Y="300" ValidateRequestMode="Inherit"></asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField2" runat="server" />
<asp:Panel ID="pnl2" runat="server" Width="881px" Height="175px" CssClass="pnl2BackGround" >
<asp:DetailsView ID="DetailsView2" runat="server" DataSourceID="SqlDataSource3" BackColor="#593B03" Height="175px" Width="881px" Font-Bold="True" ForeColor="White" PostBack = "False" AutoGenerateRows="False" DataKeyNames="WorkOrderNum" >
<Fields>
<asp:BoundField DataField="WorkOrderNum" HeaderText="WorkOrderNum" InsertVisible="False" ReadOnly="True" SortExpression="WorkOrderNum" />
<asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
<asp:BoundField DataField="CompletionDate" HeaderText="CompletionDate" SortExpression="CompletionDate" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="MachineDescription" HeaderText="MachineDescription" SortExpression="MachineDescription" />
<asp:BoundField DataField="MachineLocation" HeaderText="MachineLocation" SortExpression="MachineLocation" />
<asp:BoundField DataField="Type_of_Work_Order" HeaderText="Type_of_Work_Order" SortExpression="Type_of_Work_Order" />
<asp:BoundField DataField="Work_Required" HeaderText="Work_Required" SortExpression="Work_Required" />
</Fields>
</asp:DetailsView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:WorkOrderConnectionString6 %>" SelectCommand="SELECT [WorkOrderNum], [Requestor], [Date], [Department], [CompletionDate], [MachineDescription], [MachineLocation], [Type of Work Order] AS Type_of_Work_Order, [Work Required] AS Work_Required FROM [Master] WHERE ([WorkOrderNum] = #WorkOrderNum)">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox10" Name="WorkOrderNum" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
The Code i am using for the searching of the gridview from the header template:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Filter"] = "All";
DetailsView1.Visible = false;
TextBox10.Visible = false;
DetailsView2.Visible = false;
DetailsView3.Visible = false;
ReportViewer1.Visible = false;
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
String WorkOrderConnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["WorkOrderConnectionString3"].ConnectionString;
SqlConnection con = new SqlConnection(WorkOrderConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("spx_GetWorkOrderNum");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Filter", ViewState["Filter"].ToString());
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
TextBox TextBox92 = (TextBox)GridView1.HeaderRow.FindControl("WorkOrderNum");
}
protected void TextBox92_TextChanged(object sender, EventArgs e)
{
TextBox TextBox92 = (TextBox)sender;
ViewState["Filter"] = TextBox92.Text;
this.BindGrid();
}
I am suspecting that post back might be the issue, some where in the code it is doing an unnessary post back so when i click the imagebutton it is not getting the value
Please help me find the error in my code as the debugger is not helping me and plus this was a working code before :(
WHY THE TEXTBOX VALUE = "" INSTEAD OF THE GRIDVIEW CELL VALUE??????
Thanks
Since Gridview is a Control and TextBox is also an Control within the Gridview control we nee to do this:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1Row = (GridViewRow)imgbtn.NamingContainer;
Label FLabel = GridView1Row.Cells[2].Controls[0].FindControl("Label1") as Label;
string workordernum = FLabel.Text;// GridView1Row.Cells[3].Text;
TextBox10.Text = workordernum;
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}
Related
I'm noobie to this :)
I'm getting data from SQL Server in the page_load event handler, and that works fine with SqlDataReader.
I also added a DataTable. I want to use the data when selecting a dropdownlist.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string mainconn1 = ConfigurationManager.ConnectionStrings["SqlConnection1"].ConnectionString;
SqlConnection sqlconn1 = new SqlConnection(mainconn1);
string Sqlquery1 = "SELECT p.[Name], m.machineid,md.MachineNumber, md.HostName FROM [db].[dbo].[Machine] m INNER JOIN MachineDevice md ON md.MachineID = m.MachineID INNER JOIN property p ON m.PropertyID = p.PropertyID WHERE ([status] = '1') AND (md.DateTimeRetired IS NULL) ORDER BY md.MachineNumber";
SqlCommand sqlcomm1 = new SqlCommand(Sqlquery1, sqlconn1);
sqlconn1.Open();
SqlDataReader rd1 = sqlcomm1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rd1);
}
}
And this:
protected void Ort_SelectedIndexChanged1(object sender, EventArgs e)
{
if (Ort.SelectedValue == "Stockholm")
{
// while (rd1.read)
// {
// Machine.DataSource = rd1;
// Machine.DataTextField = "MachineNumber";
// Machine.DataValueField = "MachineNumber";
// Machine.DataBind();
// Machine.Items.Insert(0, new ListItem("-Select Machine-", "0"));
// }
}
}
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
Thanks
Sure, say we have a drop down (combo box) of some cities, and when you select the city, we fill out a gird of hotels.
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
you could in some cases "persist" the data, but the cost is just as high as in most cases hitting the database again.
so, yes, it is standard fair to re-pull that data.
example:
this markup:
<h3>Select Hotel city</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="150px" Height="30px"
DataTextField="City"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="GVHotels" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" Width="40%" OnRowDataBound="GVHotels_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" HeaderStyle-Width="120"/>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Province" />
<asp:TemplateField>
<ItemTemplate>
<button runat="server" id="cmdEditBooking"
type="button" class="btn myshadow"
onserverclick="cmdEditBooking_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, we have a combo box (dropdown list) of city to select, and then we display hotels from that city.
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo();
}
void LoadCombo()
{
string strSQL = "SELECT City FROM City ORDER BY City";
SqlCommand cmdSQL = new SqlCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select City", ""));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex >0)
{
string strSQL =
#"SELECT * FROM tblHotelsA
WHERE City = #City
ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.Text;
GVHotels.DataSource = MyRstP(cmdSQL);
GVHotels.DataBind();
}
}
And both of above use this handy helper routine:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, result:
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;
}
When click on delete link-button in gridview, Confirmation Box not appeared. I write this code but I don't know why it's not working...
<asp:GridView ID="gvwAuctionExport" runat="server" AutoGenerateColumns="false" OnRowCommand="gvwAuctionExport_RowCommand" OnRowDataBound="gvwAuctionExport_RowDataBound" OnRowDeleting="gvwAuctionExport_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="btn-group btn-group-xs" id="bgroup">
<asp:LinkButton ID="lnkInspectionDelete" runat="server" Text="Delete" CssClass="btn btn-danger" CommandArgument='<%# Eval("inspection_id") %>' CommandName="Delete"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="address" HeaderText="Address" />
<asp:BoundField DataField="city" HeaderText="City" />
<asp:BoundField DataField="state" HeaderText="State" />
</Columns>
</asp:GridView>
protected void gvwAuctionExport_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int InspectionID = Convert.ToInt32(e.CommandArgument);
string status = string.Empty;
status = DACls.DeleteInspectionByID(InspectionID);
}
}
protected void gvwAuctionExport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("lnkInspectionDelete");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record");
}
}
protected void gvwAuctionExport_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bindGridView();
}
public void bindGridView(){
DataSet DS = new DataSet();
SqlConnection DBCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
SqlCommand Cmd = new SqlCommand("USP_Inspection_Export", DBCon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(this.DS);
DataTable dt = DS.Tables[0];
this.gvwAuctionExport.DataSource = dt;
this.gvwAuctionExport.DataBind();
}
When I click on delete button and check from debugger it is not going to GridView RowDataBound function scope. I don't know what happening here?
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!
I'm having trouble with setting a HiddenField's value to a GridView item value. What I want to do is get the value of a BoundField (in this case, "FIPSCountyCode") in a GridView and store it in a HiddenField when the user clicks a button (in this case, "btnEdit") to make changes to a entry in the grid. I haven't used HiddenFields before, so I have forgotten what to do here.
The HiddenField is setup like this:
<asp:HiddenField ID="hdnFIPS" Value='<%#Eval("FIPSCountyCode")%>' runat="server" />
This is what the GridView is setup like:
<asp:GridView ID="CountyList" runat="server" AutoGenerateColumns="False" Width="90%" SkinId="PagedList" PagerSettings-Position="TopAndBottom" PagerStyle-Wrap="True">
<Columns>
<asp:BoundField HeaderText="County Code" DataField="FIPSCountyCode" />
<asp:BoundField HeaderText="State Code" DataField="StateCode" />
<asp:BoundField HeaderText="County Name" DataField="CountyName" />
<asp:BoundField HeaderText="Tax Rate" DataField="TaxRate" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" SkinID="EditIcon" OnClick="EditInfo" CommandName="DoEdit" />
<asp:ImageButton ID="DeleteButton" runat="server" SkinID="DeleteIcon" CommandName="DoDelete"
OnClientClick="return confirm('Are you sure you want to remove this item and all of its options?')"
CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="even" />
</asp:GridView>
And this is the code behind:
public partial class Admin_County_Info : CommerceBuilder.UI.AbleCommerceAdminPage
{
private string redirectString = String.Empty;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
PopulateCountyGrid();
}
protected void PopulateCountyGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT [FIPSCountyCode], [StateCode], [CountyName], [TaxRate] FROM [baird_InfoCounty]", cn);
cmd.CommandType = CommandType.Text;
cn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CountyList.DataSource = dr;
CountyList.DataBind();
}
}
catch (Exception eX)
{
}
}
#region Clicks and Event Handlers
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
protected void AddInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("~/Admin/Taxes/AddEditCountyInfo.aspx");
}
}
}
This must be a really dumb question but I'm really not sure how to proceed. Any help would be great!
You can get the value of FIPSCountyCode from the BoundField this way:
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
GridViewRow gvr = ((ImageButton)sender).NamingContainer as GridViewRow;
hdnFIPS.Value = gvr.Cells[0].Text;
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}