I've read through about 50 sites and stackoverflow questions that advise to do what I have in my code below. I've been through many variations on this, and I can't seem to get it to do anything at all.
I've been watching SQL Profiler and nothing is sent at all.
I get no errors.
All I want is a list with checkboxes I can click to change a single setting from 0 to 1. I'm sure it's me, but I'm missing it, and I've spent an embarrassingly long time on this. Thanks for any input.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames="npi"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="provcode" HeaderText="provcode"
SortExpression="provcode" />
<asp:BoundField DataField="npi" HeaderText="npi" SortExpression="npi" />
<asp:BoundField DataField="firstname" HeaderText="firstname"
SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname"
SortExpression="lastname" />
<asp:TemplateField HeaderText="Submit Y/N">
<ItemTemplate>
<asp:CheckBox ID="submitChk" runat="server" Enabled="true" AutoPostBack="True" OnCheckChanged="submit_CheckedChanged"
Checked='<%# Bind("submit") %>'/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DS_SSRS_ReportsConnectionString1 %>"
SelectCommand="SELECT [provcode], [npi], [firstname], [lastname], [submit]
FROM [DRPprovders]
ORDER BY lastname, firstname"
onselecting="SqlDataSource1_Selecting"
>
</asp:SqlDataSource>
</p>
CodeBehind:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
public partial class Pages_ProvSelect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
//int ID = (int)GridView1.DataKeys[row.DataItemIndex].Value;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
}
}
You just need to connect to the database and perform the update "manually" in that CheckedChanged method.
Something like this should work:
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
SqlConnection conn = new SqlConnection("your connection string here");
string updateQuery = "UPDATE DRPprovders SET submit = #submit WHERE npi = #npi";
SqlCommand cmd = new SqlCommand(updateQuery, conn);
// If it's checked, pass 1, else pass 0
cmd.Parameters.AddWithValue("#submit", submitChk.Checked ? 1 : 0);
cmd.Parameters.AddWithValue("#npi", npi);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
You might just be able to pass the boolean value of submitChk.Checked (rather than converting to 1's and 0's like I did), I can't remember now (and I was just typing this off the top of my head, so it's untested).
Related
Reference image of the GV
So OnSelectedIndexChanged of the dropdown in 7th cell I want to enable or disable the Remarks column (last column) of that row
Gridview.aspx
<asp:GridView ID="grdassetslist" runat="server" AutoGenerateColumns="false" BackColor="Transparent" BorderColor="Black" BorderStyle="Dashed" BorderWidth="1px" CellPadding="4"
DataKeyNames="ID" AutoGenerateSelectButton="true" CellSpacing="2" OnRowDataBound="grdassetslist_RowDataBound" HeaderStyle-ForeColor="Black" HeaderStyle-BackColor="#66ccff"
OnSelectedIndexChanged="grdassetslist_SelectedIndexChanged" HorizontalAlign="Center" HeaderStyle-CssClass="grd" RowStyle-CssClass="grd" AllowPaging="true" PageSize="15"
OnPageIndexChanged="grdassetslist_PageIndexChanged" OnPageIndexChanging="grdassetslist_PageIndexChanging">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:HiddenField ID="hdnAstID" runat="server" Visible="false" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Asset Category" ReadOnly="true" />
<asp:BoundField DataField="SAPAssetCode" HeaderText="SAP Asset Code" ReadOnly="true" />
<asp:BoundField DataField="ITAssetCode" HeaderText="IT Asset Code" ReadOnly="true" />
<asp:BoundField DataField="Make" HeaderText="Make" ReadOnly="true" />
<asp:BoundField DataField="ModelNo" HeaderText="ModelNo" ReadOnly="true" />
<asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" ReadOnly="true" />
<asp:BoundField DataField="AssetStatus" HeaderText="Current Status" ReadOnly="true" />
<asp:TemplateField HeaderText="Change Status To">
<ItemTemplate>
<asp:DropDownList ID="ddl_each_asset_status" runat="server" Width="100px" Height="25px" CssClass="dd" AutoPostBack="true" OnSelectedIndexChanged="ddl_each_asset_status_SelectedIndexChanged1" CausesValidation="false" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CurrentUser" HeaderText="CurrentUser" ReadOnly="true" />
<asp:TemplateField HeaderText="Remarks for Status change">
<ItemTemplate>
<asp:TextBox ID="txtrmrks" runat="server" placeholder="Remarks (if any)" ReadOnly="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Assests" HeaderText="" ReadOnly="true" />--%>
</Columns>
<HeaderStyle HorizontalAlign="Center"/>
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
GridLoad.apx.cs
con.Open();
DropDownList DropDownList1 = (e.Row.FindControl("ddl_each_asset_status") as DropDownList);
SqlCommand cmd = new SqlCommand("select ID,Code[Title] from tbl_assetstatus (nolock) where ID<>2 and IsActive=1 order by ID", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Title";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Status", "0"));
SelectedIndexChanged event:
protected void ddl_each_asset_status_SelectedIndexChanged1(object sender, EventArgs e)
{
//Code to Enable or Disable the remarks column of that row of which the dropdown was changed?
}
Please add the code for SelectedIndexChanged for this.
Thanks in Advance
If you using GridView, then I doubt this is a .net core application?
And really, to help us out here - try posting at LEAST SOME of your gridviewe markup, as then we not trying to play a game of darts in a room with the lights out.
Assuming a GV like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table table=table-hover" Width="800px"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="First name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField="City"
DataValueField="City"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="lbl1" runat="server" Height="179px" Width="450px" TextMode="MultiLine">
</asp:Label>
</div>
Code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT City FROM City ORDER BY City";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstCity.Load(cmdSQL.ExecuteReader());
cmdSQL.CommandText =
"SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
Ok, and now the code for the combo box (dropdown list). We assume auto-post back, so the code is thus this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string cr = System.Environment.NewLine;
string sResult =
$"Row index = {gRow.RowIndex} \n DataBase PK = {PK} <br/>" +
$" Hotel = {gRow.Cells[3].Text} <br/>" +
$"Combo Box selection = {cboCity.Text}";
lbl1.Text = sResult;
}
and thus we see/get this:
Edit2:
I should also note the following additonal information:
Of course I have to fill/load the drop down.. and that is done in row data bound event. Eg this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
cboCity.Items.Insert(0,new ListItem("Select", ""));
if (gData["City"] != DBNull.Value)
{
cboCity.Text = gData["City"].ToString();
}
}
}
Also, note how I don't care (or bother) with the GV selected index changed event. I really don't need it. I as noted, simple set autopost-back = true.
Last but not least?
you of course cannot build ANY working webforms page if you attemptto load up data in on-load but FORGET to check isPostback.
Since any button click, any post-back, or anything causing a post-back will of course trigger the page load event again, and BEFORE any of your other events. Thus, you need to ALWAYS ensure that you only load up the information one time on page load, since if you re-load the gv, or even a dropdown, then you tend to lose that choice by the user being made.
thus, that all imporant !IsPostBack stub is required for most pages.
Eg this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
next up:
Since the dropdown list has the one grid row, then you are free to get data, hide data, enable or do whatever you please.
Just keep in mind that
For built in "databound" columns, you use the cells[] colleciton.
For any templated control, then you use gRow.FindControl("control name here")
So, since your "goal" in question is to operate on "txtrmrks" then that is a templated column, and thus we have to use findcontrol.
Say, like this:
air code warning!!!
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
TextBox txtrmrks = (TextBox)gRow.FindControl("txtrmrks");
if (cboCity.Text == "Banff")
{
// disable the txtrmrks box
txtrmrks.Enabled = false;
}
}
You also not clear if you are going to working the value returned from the cbo box as "id", or "Title"
I suggest this way, and not to use ".Text" of the cbo, but this:
cboCity.SelectedItem.Value (gets value - ID)
cboCity.SelectedItem.Text (gets Text - Title)
if (cboCity.SelectedItem.Text)
I'm implementing a search bar to filter GridView1. I followed this tutorial but when it doesnt work. I want to filter the UserID and show only the specific output match the user input. I clicked on search but nothing work, it just refreshed the page and nothing else.
aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Manager.Master" AutoEventWireup="true" CodeBehind="ExceptionReport.aspx.cs" Inherits="Bracelet.ExceptionReport" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-md-10">
<div class="content-box-large">
<div class="panel-heading">
<div class="panel-title">Admin Log Report</div>
</div>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server"/>
<div class="panel-body">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
</div>
</div>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users">
</asp:LinqDataSource>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users" Where="UserRole == #UserRole">
<WhereParameters>
<asp:Parameter DefaultValue="Admin" Name="UserRole" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
</div>
</asp:Content>
Full code .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Bracelet
{
public partial class ExceptionReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT UserID, UserName, UserEmail, logtime FROM [User] WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserID ", txtSearch.Text.Trim());
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
}
}
Not too bad.
but, there are few errors and issues.
first up, you have search button - but it has no "id" assigned.
You probably should get in the habit of simple drag + drop the button in from the tool box.
So, we now have this for the button and the grid:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
NOTE carefull in above, how we gave the button a "ID"
So, our basic code to load up the grid?
FYI: huge love, hugs, high-5's for checking is-post back!!!
(always, always do that!!!).
So, our code to load things up can thus look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.BindGrid();
}
void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT UserID, UserName, UserEmail, logtime FROM [User]", con))
{
// optional text box filter (blank = all)
if (txtSearch.Text != "")
{
cmd.CommandText += " WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Parameters.Add("#UserID", SqlDbType.Text).Value = txtSearch.Text;
}
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Note how we did not need that data adaptor - not needed.
However, we still not created the code stub for the button click (that's why your code is not working - you did not give your button a "id"
So, in the designer - double click on the button. That will create the "event" for you, and jump to the code editor, and we have this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
this.BindGrid();
}
so, in general - don't type in the "event" stubs for a button - double click on the button - it will create + wire it up for you.
Note close, if I flip back to mark-up, the button has become this:
<asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />
I've searched for two days now and can't find a solution for my problem. I'm programming a webpart with connection to a database with Visual Studio.
So I've made a GridView to show some data listed in the database and the user is able to edit and update the data in it. Before you see the GridView, you have to click the button "load table". But when I click on "edit" on the GridView, the GridView dissapears and only shows up when I click the button "load table" again, with the GridView in edit-mode.
ASP
<asp:Button ID="btnload" runat="server" Text="load table"
onclick="btnload_Click" />
<asp:GridView ID="gridtable" runat="server" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
CellPadding="4" EnableModelValidation="True"
OnRowCancelingEdit="gridtable_RowCancelingEdit"
OnRowEditing="gridtable_RowEditing"
OnRowUpdating="gridtable_RowUpdating" >
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<Columns>
<asp:TemplateField HeaderText="P_number">
<ItemTemplate>
<%#Eval("P_number")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="textbox1" runat="server" Text='<%#Eval("P_number")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="lastname">
<ItemTemplate>
<%#Eval("lastname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="textbox2" runat="server" Text='<%#Eval("lastname")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PN_ch">
<ItemTemplate>
<%#Eval("PN_ch")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="textbox3" runat="server" Text='<%#Eval("PN_ch")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="lastname_ch">
<ItemTemplate>
<%#Eval("lastname_ch")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="textbox4" runat="server" Text='<%#Eval("lastname_ch")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="workplace">
<ItemTemplate>
<%#Eval("workplace")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="textbox5" runat="server" Text='<%#Eval("workplace")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
public SqlDataSource datasource;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnload_Click(object sender, EventArgs e)
{
openConnection(getconstring());
gridtable.AutoGenerateColumns = false;
gridtable.AutoGenerateEditButton = true;
datasource = new SqlDataSource(getconstring(), "SELECT * FROM T_Employees");
BindData();
}
public void BindData()
{
try
{
gridtable.DataSource = datasource;
gridtable.DataBind();
}
catch (Exception e)
{
//Do something
}
}
protected void gridtable_RowEditing(object sender, GridViewEditEventArgs e)
{
gridtable.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridtable_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//get EditIndex
GridViewRow row = gridtable.Rows[e.RowIndex];
// save changes
string pnumber = ((row.Cells[1].Controls[0]).ToString());
string lastname = ((row.Cells[2].Controls[0]).ToString());
string pn_ch = ((row.Cells[3].Controls[0]).ToString());
string lastname_ch = ((row.Cells[4].Controls[0]).ToString());
string workplace = ((row.Cells[5].Controls[0]).ToString());
//Update
datasource.UpdateCommand = "UPDATE T_Employees SET P_number='"+pnumber+"', lastname='"
+lastname+"', PN_ch='"+pn_ch+"', lastname_ch='"
+lastname_ch+"', workplace='"+workplace+"'";
datasource.Update();
//reset EditIndex
gridtabelle.EditIndex = -1;
//Bind data
BindData();
}
protected void gridtable_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridtable.EditIndex = -1;
BindData();
}
You need to store the datasource in session in the button click:
protected void btnload_Click(object sender, EventArgs e)
{
openConnection(getconstring());
gridtable.AutoGenerateColumns = false;
gridtable.AutoGenerateEditButton = true;
datasource = new SqlDataSource(getconstring(), "SELECT * FROM T_Employees");
Session["datasource "] = datasource
BindData();
}
Then change your bind to this:
public void BindData()
{
try
{
gridtable.DataSource = Session["datasource "] ;
gridtable.DataBind();
}
catch (Exception e)
{
//Do something
}
}
You also need to add this to the web.config:
<system.web>
<pages enableSessionState="true">
</system.web>
Or this to the page:
<%#Page enableSessionState="true">
You may just declare your datasource as in your aspx file and you're done. If you then need to bind your grid after a button click, then you have to store somewhere (eg. viewstate) a flag (boolean value) to indicate if your grid has to be binded or not. Then bind the grid only if that flag is true.
Don't need to use session at all.
Eg:
protected void Page_Load(object sender, EventArgs e)
{
if (!isPostBack){
ViewState["FLAG"] = false;
}
else{
if ((bool)ViewState["FLAG"]) BindData();
}
}
protected void btnload_Click(object sender, EventArgs e)
{
ViewState["FLAG"] = true;
}
Looking # previous answers, please consider that even if you choose ViewState or Session (each of these have their own advantages / disadvantages), you don't need to store ridundant data. In your case, just a single bit is enough, as you have the code - in your page - to build/bind the data source without storing it interely.
I am working on a college project and have a gridview that I have to add more rows to.
I have two text fields and a button.
Everything seems to be fine except the button part of the code in the .cs file
What am I doing wring?
Its to make a list of Wines with an ID and a Title and a Year:
Wine.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Wine.aspx.cs" Inherits="WineNotProject2.AdminPages.Wine" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<br /><br />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
</Columns>
</asp:GridView>
<p><asp:Label ID="lblTitle" runat="server" Text="Wine Title"></asp:Label><br />
<asp:TextBox ID="txtTitle" runat="server" Width="176px"></asp:TextBox><br />
<p><asp:Label ID="lblYear" runat="server" Text="Wine Year"></asp:Label><br />
<asp:TextBox ID="txtYear" runat="server" Width="176px"></asp:TextBox><br />
</p>
<asp:Button ID="btnAdd" runat="server" Text="Add Wine" OnClick="btnAdd_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [Title], [Year] FROM [Wine]">
</asp:SqlDataSource>
</asp:Content>
Wine.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WineNotProject2.AdminPages
{
public partial class Wine : System.Web.UI.Page
{
private WineEntities10 ent2 = new WineEntities10();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RefreshGrid();
}
}
private void RefreshGrid()
{
GridView2.DataSource = ent2.Wines.ToList();
GridView2.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
}
}
}
UPDATE:
The error message is:
Error 3 'WineNotProject2.AdminPages.Wine' does not contain a definition for 'Year' and no extension method 'Year' accepting a first argument of type 'WineNotProject2.AdminPages.Wine' could be found (are you missing a using directive or an assembly reference?) C:\Visual Studio 2010\Projects\WineNotProject7\WineNotProject2\AdminPages\Wine.aspx.cs 30 20 WineNotProject2
I think you need to call RefreshGrid after you have added the new Wine:
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
RefreshGrid(); // <-------
}
Maybe you also need to parse the year to int:
w2.Year = int.Parse(txtYear.Text);
The problem is you have two classes with same name Wine.
public partial class **Wine** : System.Web.UI.Page
**Wine** w2 = new **Wine**();
Rename ASP.Net page's name to WineList so that
its class name should become public partial class **WineList**
Your code was looking good ,But you miss call the RefreshGrid() end of add button
for
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
**RefreshGrid**
}
If ent2.SaveChanges(); is not working ,then use ent2.SubmitChanges();
I am adding a dropdown to gridview using template field as:
<asp:TemplateField HeaderText="Change Color">
<ItemTemplate>
<asp:DropDownList ID="dropdownid" DataSourceID="sqldatasource_id" DataTextField="username"
BackColor="GrayText" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AppendDataBoundItems="True" runat="server" AutoPostBack="True">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
</asp:DropDownList>
SqlDataSource is:
<asp:SqlDataSource ID="sqldatasource_id" runat="server" ConnectionString="<%$ ConnectionStrings:crudconnection %>"
SelectCommand="SELECT [username] FROM [crudtable]"></asp:SqlDataSource>
Indexchange-Event is as :
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
}
I want to highlight a row when any value from the corresponding dropdownlist is selected.
How can i do it?
Thanks in advance.
i tried it:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red;
But still it is giving a exception as follow when-ever i select any value from any dropdownlist.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
I am getting index number of selected row as already mentioned.can't i increment it from there and can use back-color property too?
Can you give this a try:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red inside your GridView1_SelectedIndexChanged?
It should set the background color of the selected row to a red color
Try GridView_SelectedIndexChanging(). Here is how:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//This is current row. Set it to default color
GridView1.SelectedRow.BackColor = System.Drawing.Color.White;
//This is selected row. Set it to color you wish
GridView1.Rows[e.NewSelectedIndex].BackColor = System.Drawing.Color.Black;
}
Its working.I made changes like below.
int abc=row.rowindex+3;
GridView1.Rows[abc].BackColor = Color.Yellow;
Thanks for support.
function ChangeRowColor(row) {
row = parseInt(row) + 1;
if (previousRow == row)
return; //do nothing
else if (previousRow != null) {
document.getElementById("MainContent_gvSimulationManager").rows[previousRow].style.backgroundColor = previouscolor;
}
previouscolor = document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor;
document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor = "#888888";
previousRow = row;
//Disable and enable Session
var simulationStatus = document.getElementById("MainContent_gvSimulationManager").rows[row].cells[3].innerText;
EnableAndDisable(simulationStatus);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="pub_id" HeaderText="pub_id" />
<asp:BoundField DataField="pub_name" HeaderText="pub_name" />
<asp:BoundField DataField="city" HeaderText="city" />
<asp:BoundField DataField="state" HeaderText="state" />
<asp:BoundField DataField="country" HeaderText="country" />
<asp:ButtonField Text="Click" CommandName="Select" ItemStyle-Width="30" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="msg" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
sql = "select * from publishers";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string pName = GridView1.SelectedRow.Cells[1].Text;
grdCList.SelectedRow.Cells[3].ForeColor = System.Drawing.Color.Red;
}