GridView Order of Operations - c#

No error as such, but the way I have it setup, the GridView renders on Page_Load, it would seem that then the rest of operations that I have setup don't seem to fire.
Any ideas on the order? Been at it for hours now :(
<asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True" EmptyDataText="No Records Found" AutoGenerateColumns="False" DataSourceID="showOrders" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Height="74px" Width="394px">
<Columns>
<asp:TemplateField HeaderText ="Pizza Type" SortExpression="pizza_id">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("pizza_id") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mylabel" runat="server" Text='<%#Bind("pizza_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="quantity" HeaderText="Quanity" SortExpression="quantity" />
<asp:BoundField DataField="pizza_size" HeaderText="Pizza Size" SortExpression="pizza_size" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="showOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>"></asp:SqlDataSource>
Code Behind:
public partial class order_details : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string username = User.Identity.Name;
showOrders.SelectParameters.Add("username", username);
showOrders.SelectCommand = "SELECT [pizza_id], [quantity], [pizza_size] FROM [orders] WHERE ([username]=#username)";
}
protected void GridView1_Databound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
row.Visible = row.RowIndex.Equals(1);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string value = e.Row.Cells[7].Text;
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "1")
{
myLabel.Text = "Big Cheese";
}
else if (value == "2")
{
myLabel.Text = "BBQ Beef";
}
else if (value == "3")
{
myLabel.Text = "Chicken and Pineapple";
}
else if (value == "4")
{
myLabel.Text = "Pepperoni Feast";
}
else if (value == "5")
{
myLabel.Text = "Vegetarian";
}
}
Any help would be appreciated.
Thanks Kindly.

You need to wire up the offending events:
<asp:GridView ID="GridView1" runat="server"
ShowHeaderWhenEmpty="True"
EmptyDataText="No Records Found"
AutoGenerateColumns="False"
DataSourceID="showOrders"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2"
Height="74px" Width="394px"
OnRowDataBound="GridView1_RowDataBound"
OnDataBound="GridView1_Databound">

Related

How to find TextBox in GridViewRow edit mode

I have tried several so called answers for this and it has me lost. I am simply trying to default a TextBox Text value with today's date and time, but I cannot find the control when I click LinkButton with CommandName "Edit".
Here is my gridview...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
<ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
<asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
The LinkButton btnEDT works and puts the gridview in edit mode. But in code behind I cannot find "txtReturned".
This is what I've tried so far...
protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIdx = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvSignInRegister.Rows[rowIdx];
if (row != null && row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
//row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
For some reason the rowIdx is always 0. Why? I thought a row index of 0 meant the header of the gridview control.
I've also tried using the NamingContainer that most other people have suggested in other posts, but that returns a blank (I suspect new?) GridViewRow.
ie
GridViewRow row = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);
UPDATE
I found this, which is exactly the problem I am having, but the solution via the RowEditing still does not find the textbox!
However the RowDataBound() solved it! Read my answer below.
The answer was in getting into the editmode version of the GridView itself and then find the control!
As per this post...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
<Columns> ...etc...
protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
Use Container.DisplayIndex instead of Container.DataItemIndex
But I dont think you will get textBox control if you are placing it in EditItemTemplate
If your expectation is editing operation then please use the below code
HTML
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit" OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>' runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Code Behind:
protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
{
gvSignInRegister.EditIndex = e.NewEditIndex;
List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
decimal qty = 0;
decimal.TryParse(txtQty.Text, out qty);
if (qty < 0)
{
lblErrorSummary.InnerText = "Please provide valid Quantity";
lblErrorSummary.Visible = true;
return;
}
itemList[e.RowIndex].Quantity = qty
ViewState["ItemList"] = itemList;
gvSignInRegister.EditIndex = -1;
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}

How can remove/replace substring from GridView Column?

I have below GridView:
I want to remove 0:00:00 from date column, if exists. I change dataformatstring but that remove 9:09:15 too.
I use auto-generate fields and DataBind on .cs file.
I tried Replace, but does not work:
e.Row.Cells[0].Text = e.Row.Cells[0].Text.Replace("0:00:00"," ");
How can I do that?
Gridview:
<asp:GridView ID="GridView4" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical" Width="98%"
Height="100%" onrowdatabound="GridView4_RowDataBound" RowStyle-HorizontalAlign="Center" >
<AlternatingRowStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
Code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
OleDbConnection Connection6;
using (Connection6 = new OleDbConnection("Provider=MSDAORA.1;Data Source=XXXXXX:1521/orcl;Persist Security Info=True;Password=XXXXXXX;User ID=XXXXXX;"))
{
string sqlQuery = "select * from db.user";
using (OleDbDataAdapter cmd = new OleDbDataAdapter(sqlQuery, Connection6))
{
Connection6.Open();
DataTable dt = new DataTable();
cmd.Fill(dt);
GridView4.DataSource = dt;
GridView4.DataBind();
Connection6.Close();
}
}
}
catch (Exception)
{
}
}
You can use RowDataBound event, then label control using findcontrol
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblDate" Text='<%# Eval("Date") %>' runat="server"></asp:Label>
.....
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var lbl = e.Row.FindControl("lblDate") as Label;
lbl.Text = lbl.Text.Replace("0:00:00", "");
}
}
If you don't have Template Field and using Bound Field then Use
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.Cells[0].Text.Contains("0:00:00"))
e.Row.Cells[0].Text = e.Row.Cells[0].Text.Replace("0:00:00", "");
}
}

Change background color of gridview row while processing

What I need to do is to highlight each row when it is processing to show the process progress, the gridview may contain almost one thousands of row. below is the code I have written but which doesn't work.
Please can someone help me.
<
asp:GridView ID="gdview1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Font-Names="Calibri"
Font-Size="Small" AutoGenerateColumns="False"
OnRowDataBound="gdview1_RowDataBound"
OnSelectedIndexChanged="gdview1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" runat="server" />
</HeaderTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" DataField="ColNUM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row#">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ColNUM" HeaderText="Contract #" />
<asp:BoundField DataField="Col1" HeaderText="Suffix" />
<asp:BoundField DataField="Col2" HeaderText="First Name" />
<asp:BoundField DataField="Col3" HeaderText="Last Name" />
<asp:BoundField DataField="Col4" HeaderText="Street" />
<asp:BoundField DataField="Col5" HeaderText="City" />
<asp:BoundField DataField="Col6" HeaderText="Zip" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butChargeCreditCards_Click(object sender, EventArgs e)
{
DataTable tblContrts = (DataTable) Session["tblContrts"];
foreach (GridViewRow row in gdview1.Rows)
{
CheckBox chkbx = (CheckBox) row.FindControl("chkNUM");
if (chkbx != null && chkbx.Checked)
{
gdview1_SelectedIndexChanged(row,e);
string SS = chkbx.Text.ToString();
string strResults = method1;
}
}
}
protected void gdview1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdview1.Rows)
{
if (row.RowIndex == gdview1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
}
}
}
}
}
Have you tried it by using the "OnRowDataBound" or "OnRowCreated" Event of the Grid and write the color-highliting in code behind?
Something like this?
http://www.java2s.com/Code/ASP/ADO.net-Database/UsingtheRowCreatedEventtoprogrammaticallychangethestyle.htm
But maybe you have a problem because the loading would be too fast to really notice?

Gridview linkbutton postbackurl change on page load event

I have a gridview with a linkbutton, the url linkbutton is assigned using a code by replacing a key word with a name from the DB.
all works fine, except that when I click the back button in browser and try different link I get this error:
"The HTTP verb POST used to access path '/System.Web.UI.WebControls.Label' is not allowed"
below is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var HyperLink = row.FindControl("LinkButton1") as LinkButton;
var RepID = row.FindControl("Label1") as Label;
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", RepID.Text + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="report_id" DataSourceID="SqlDataSource1" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("report_name")%>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("report_subject")%>'></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
I think the problem might be that you're doing your binding at the Page_Load stage of the page life cycle. Try moving your foreach code to a
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var HyperLink = e.Row.FindControl("LinkButton1") as LinkButton;
//var RepID = row.FindControl("Label1") as Label;
//You should be able to access your field without referencing the label too
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var myField = row.Field<string>("report_name");
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", myField + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}

gridview problem

i have a problem with my gridview contains a textbox to set a date.
<asp:gridview ID="Gridview1" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" CellPadding="8" ForeColor="#333333"
GridLines="None" CellSpacing="5" Height="361px" Width="748px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="nome" HeaderText="Nome Utente"
SortExpression="nome" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="titolo" HeaderText="Titolo Libro"
SortExpression="titolo" >
<ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField DataField="Expr1" HeaderText="Data Restituzione Prevista"
ReadOnly="True" SortExpression="Expr1" >
<ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:TemplateField
HeaderText="Data Restituzione" SortExpression="Expr2">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Expr2") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Expr2") %>'
AutoPostBack="True" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:gridview>
And it is my asp.cs file:
namespace Utenti_Biblio
{
public partial class prestiti : System.Web.UI.Page
{
bool changed = false;
protected void Page_Load(object sender, EventArgs e)
{
selectRow();
}
public void selectRow()
{
foreach (GridViewRow row in this.Gridview1.Rows)
{
TextBox textBox = (TextBox)row.Cells[3].FindControl("TextBox1");
string a = textBox.Text;
if (a != "")
{
row.Cells[3].FindControl("TextBox1").Visible = false;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
changed = true;
}
// salva
protected void Button1_Click(object sender, EventArgs e)
{
if (changed)
{
foreach (GridViewRow row in this.Gridview1.Rows)
{
TextBox textBox = (TextBox)row.Cells[3].FindControl("TextBox1");
string qry = "UPDATE b_prestiti SET data_restituzione ='" + textBox.Text + "' WHERE id_utente = '" + row.Cells[1].ToString() + "'";
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
OleDbCommand cmd = conn.CreateCommand();
OleDbDataReader reader = null;
conn.Open();
cmd.CommandText = qry;
reader = cmd.ExecuteReader();
ClientScript.RegisterStartupScript(this.GetType(), "conferma", "alert('Data Restituzione inserita!');window.location='Default.aspx';", true);
reader.Close();
conn.Close();
}
}
}
}
}
How i do to update the database when i set the date into my textbox?
The query string is not correct. Thanks!
Instead of the ExecuteReader() use ExecuteNonQuery(), that might do the trick.
GxG is right. ExecuteReader() is use to fetch the single record(Column) while to DML(Data Manipulation Language, like INSERT,DELETE,UPDATE) we use ExecuteNonQuery().

Categories

Resources