How can I understand which columns value when I press the button? - c#

I try to write data grid in aspx. In my database there is a column which name is 'PROJECT_NAME'. I want these columns in my data grid, then I add second column (editbox) to add values every each of project. This is all in grid view, and I add button in form. When I press the button how can I understand which columns value belong which project?
I mean, for example
Row value : A project 2 Column value : 50
Row value : B project 2 Column value : 60
Row value : C project 2 Column value : 70
I want to know when I press button 1. project value 50 how can ı understand this?
This is my aspx code :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<style type="text/css">
.style1
{
width: 78px;
}
.style2
{
width: 426px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 561px">
<table style="width: 100%; height: 556px;">
<tr>
<td>
</td>
<td>
<table style="width:100%;">
<tr>
<td class="style1">
Ay</td>
<td>
<asp:TextBox ID="ay" runat="server"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td class="style1">
Yıl</td>
<td>
<asp:TextBox ID="yil" runat="server"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td class="style1">
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="portföy" runat="server"
CellPadding="3" GridLines="Horizontal"
AutoGenerateColumns="False"
DataKeyNames="PRJ_PROJECT_NAME" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" Font-Bold="False" Font-Names="Verdana"
Font-Overline="False" Font-Size="Smaller" Width="1000px"
>
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
<asp:TemplateField HeaderText="PRJ_PROJECT_NAME" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblProjeTT" runat="server" Text='<%# Bind("PRJ_PROJECT_NAME") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Miktar (a/g)" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox runat="server" id="txtField1" Text='<%# Bind("TAMAMLANMA_YUZDESI") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" id="txtField1" Text='<%# Bind("TAMAMLANMA_YUZDESI") %>'/>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ShowHeader="False" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<EditRowStyle BackColor="#FFFFA8" ForeColor="Black" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>
<table style="width:100%;">
<tr>
<td class="style2">
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
Width="149px" />
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
csOra cOra;
string oraTns = ConfigurationManager.AppSettings["TNS"];
string oraUserName = ConfigurationManager.AppSettings["OraUserName"];
string oraPassword = ConfigurationManager.AppSettings["OraPassword"];
protected void Page_Load(object sender, EventArgs e)
{
cOra = new csOra(oraTns, oraUserName, oraPassword);
if (cOra.OraCnn.State != ConnectionState.Open)
{
MessageBox.Show("Oracle ile bağlantı kurulamadı...");
return;
}
try
{
if (!IsPostBack)
{
setGrid();
}
}
catch (OleDbException ex)
{
Response.Write(#"Oracle Error:" + ex.Message);
return;
}
catch (Exception ex)
{
Response.Write(#"Error:" + ex.Message);
return;
}
}
void setGrid()
{
string sSQL = #"SELECT PRJ_PROJECT_NAME,TAMAMLANMA_YUZDESI
FROM PPIGANTT.KOKTEYL_TABLE_3
WHERE PRJ_PROJECT_NAME like '%d%'
ORDER BY Request_id";
try
{
OleDbDataAdapter oDa = new OleDbDataAdapter(sSQL, cOra.OraCnn);
DataTable portföy_ = new DataTable("KOKTEYL_TABLE_3");
oDa.Fill(portföy_);
if (portföy_.Rows.Count > 0)
{
portföy.DataSource = portföy_;
portföy.DataBind();
}
else
{
portföy_.Rows.Add(portföy_.NewRow());
portföy.DataSource = portföy_;
portföy.DataBind();
int TotalColumns = portföy.Rows[0].Cells.Count;
portföy.Rows[0].Cells.Clear();
portföy.Rows[0].Cells.Add(new TableCell());
portföy.Rows[0].Cells[0].ColumnSpan = TotalColumns;
portföy.Rows[0].Cells[0].Text = "No Record Found";
}
}
catch (OleDbException ex)
{
Response.Write(#"Oracle Error:" + ex.Message);
return;
}
catch (Exception ex)
{
Response.Write(#"Error:" + ex.Message);
return;
}
}
void UpdatePortföy(string Portföy, int bütçe )
{
string sSQL = #"BEGIN UPDATE PPIGANTT.KOKTEYL_TABLE_3
SET TAMAMLANMA_YUZDESI = " + bütçe + #"WHERE PRJ_PROJECT_NAME ='"
+ Portföy + #"' ; COMMIT; END;";
string sErr = "";
try
{
cOra.ExecNonQuery(sSQL, out sErr);
}
//setGrid();
catch (OleDbException ex)
{
Response.Write(#"Oracle Error:" + ex.Message);
return;
}
catch (Exception ex)
{
Response.Write(#"Error:" + ex.Message);
return;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
/* what can I write here to understand whic column value ?*/
}
}
Thanks.

Inside of Button1_Click you need need to loop through all the rows in the GridView and do a FindControl on each row to get the label and textbox. From that you can determine what the PRJ_PROJECT_NAME and values in the textbox are.
Here is an example:
Default.aspx
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblLabel" runat="server" Text='<%# Bind("Number") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtData" runat="server" Text='<%# Bind("Value") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create some fake data and bind it to the gridview
var data = new List<TheData>();
foreach(var num in Enumerable.Range(1, 4))
{
var newData = new TheData();
newData.Number = num.ToString();
newData.Value = num;
data.Add(newData);
}
gvData.DataSource = data;
gvData.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (var index = 0; index < gvData.Rows.Count; ++index)
{
var row = gvData.Rows[index];
var lblLabel = row.FindControl("lblLabel") as Label;
var txtData = row.FindControl("txtData") as TextBox;
//Here is where the values are grabbed, at this point you can do what you need to.
var number = lblLabel.Text;
var value = txtData.Text;
}
}

one solution I have used before takes advantage of the CommandArgument attribute of the button. You can set the CommandArgument='<% Eval("ColumnValueYouWant") %>' and each button will get the value for the column in it's row. Then, in the click event you can parse the object sender back into a Button and access the CommandArgument value.

Related

How to get Textbox from <ItemTemplate> in Repeater ASP Net

I have a product catalog page. When you click on the "Add Product" button, page with a cart shows up. This page has a table with an ItemTemplate inside it. Is there any way to get the value from the textBox located inside that ItemTemplate and change the value in the column Total cost in the table by clicking the button? The main problem is that I cannot access the textBox since it's in the . Thank you.
Catalog page:
Cart page:
CartView.aspx
MasterPageFile="~/Page/Store.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="bodyContent" runat="server">
<div id="content" style="margin-left: 7%;">
<style>
#import url("/css/tableCart.css");
#import url("/css/ButtonsCart.css");
</style>
<h2 style="padding: 14px; color:Highlight;">Ваша корзина</h2>
<h3 style="padding: 14px; color:Highlight;">Товары, которые вы добавили в корзину, представлены здесь</h3>
<table id="Table1" V class ="simple-little-table">
<thead>
<tr>
<th></th>
<th>Название</th>
<th>Цвет</th>
<th>Глубина</th>
<th>Ширина</th>
<th>Цена</th>
<th>Количество</th>
<th>Итого</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="Repeater1" ItemType="Line.Models.CartLine"
SelectMethod="GetCartLines" runat="server" EnableViewState="false">
<ItemTemplate>
<tr>
<td><asp:Image ID="Image1" runat="server" style="height:45px; " ImageUrl=<%# Item.Product.Img %> /></td>
<td> <%# Item.Product.NameProduct %> <%# Item.Product.TypeProducts %></td>
<td><%# Item.Product.Colors %></td>
<td>
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<asp:Button ID="cmdUpdate" OnClick="cmdUpdate_Click1" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>'/>
</td>
<td><%# Item.Size.Depth%></td>
<td><%# Item.Product.Price%></td>
</td>
<td>
<td>
<asp:Label ID="Label2" runat="server" Text="<%# ((Item.Quantity *
Item.Product.Price))%>"></asp:Label>
</td>
<td>
<asp:Label ID="txtAmount" runat="server" Text=""></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
<tfoot>
<tr>
<td colspan="3">Итого:</td>
<td colspan="2" ><%= CartTotal.ToString("c") %></td>
</tr>
</tfoot>
</table>
</div>
</asp:Content>
CartView.aspx.cs
using Line.Helpers;
using Line.Models;
using Line.Models.Repository;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Line.Page
{
public partial class CartView : System.Web.UI.Page
{
protected void Page_Load(object sender, RepeaterCommandEventArgs e)
{
}
public IEnumerable<CartLine> GetCartLines()
{
return SessionHelper.GetCart(Session).Lines;
}
public decimal CartTotal
{
get
{
return SessionHelper.GetCart(Session).ComputeTotalValue();
}
}
public string CheckoutUrl
{
get
{
return RouteTable.Routes.GetVirtualPath(null, "checkout",
null).VirtualPath;
}
}
public string ReturnUrl
{
get
{
return SessionHelper.Get<string>(Session, SessionKey.RETURN_URL);
}
}
protected void cmdUpdate_Click1(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items[Convert.ToInt32(e.CommandArgument)];
TextBox tQty = (TextBox)rRow.FindControl("txtQty");
Label tAmount = (Label)rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text;
}
}
}
}
Ok, so you can set the index of the button, and pick this up in the Repeater "item command"
So, for your button, you can/want say this:
I have qty, price, and amount in the repeater. and button.
So, the markup can look like this:
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, you are now free to enter Qty, amount in any of the repeated items.
I have this:
Now, my repeater is going accross - and I think you should be using a listview since that better supports a grid + columnar layout - but it really don't mater (listview, gridview, repeater - they all work the same).
So, note how in our button we have both command Name, and command argument. In command argument I pass the row of the repeater.
So, the code looks like this:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// update button in repeater clicked
// update amount based on qty, and price
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items(e.CommandArgument);
TextBox tQty = rRow.FindControl("txtQty");
TextBox tPrice = rRow.FindControl("txtPrice");
TextBox tAmount = rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text * tPrice.Text;
}
}
So, just pass the "index" of the repeater row as per above. We used this expression as command argument:
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, once you have the Item Index (row index), then you can run code against the one row and change that row as per above.
Edit:
So the full markup I have is this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>' />
<div>
City : <asp:DropDownList ID="cboCity" runat="server" DataTextField="City"
DataValueField="City" Width="110px">
</asp:DropDownList>
<div style="float:right;text-align:center;margin-left:4px;">
<asp:Button ID="cmdAddCity" runat="server" Text="+" OnClick="cmdAddCity_Click" Height="16px" Width="12px" Font-Size="XX-Small" cssclass="btnPad" OnClientClick="AddCity();return false"/>
</div>
</div>
Active: <asp:CheckBox ID="chkActive" runat="server" Checked = '<%# Eval("Active") %>'/>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
The code to load up this repeater is this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
LoadGrid();
}
public void LoadGrid()
{
cmdSQL.Connection.Open();
strSQL = "SELECT ID, FirstName, LastName, HotelName, City, Active from tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
rstTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = rstTable;
Repeater1.DataBind();
}
}
so the above fills out the repeater - as noted, for a grid like layout, I would use a listview. Drag a list view into a web page.
use the wizards to connect to the database. Now blow out all the templates, only leave the itemtemplate.
Your code to load up the grid - same as above.
now, in place of the repeater as per previous screen shots?
You get this:
So your multiple lines that your building? They should be based on and around a listview. And each row can thus be grabbed, and addressed just as I did per above.
Do a google for listview examples - there is a like a billion examples.
Once you have this setup, then each row is a "thing" that repeats for you automatic based on the data from the table.
The markup for the list view - it again quite much follows the same ideas and concepts as a repeator. the listview for above looks like this:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
<ItemTemplate>
<tr style="">
<td><asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td><asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Eval("Active") %>' Enabled="false" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">ID</th>
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">Active</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>

ASP.net 4.6 c# Set text when page opens

I have a page that allows the user to click the generate button to assign a random code to a text box. I want the text box to be assigned a default random code when the page opens. The text that is assigned needs to use the generate code method that the button is using. Where do I assign the text to the box when the page opens? I think it's the onload from the microsoft docs.
for example
// Override the OnLoad method to set _text to
// a default value if it is null.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (_text == null)
_text = "Here is some default text.";
}
but I Don't know where to put that.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="XMLAddUpdateDelete.aspx.cs"
Inherits="xmlInsertUpdateDelete.XMLAddUpdateDelete" %>
<!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>
<table>
<tr>
<td>
ID
</td>
<td>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Instructor</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:TextBox ID="txtDesignation" runat="server" Visible="False"></asp:TextBox>
</td>
</tr>
<tr>
<td>
CourseID
</td>
<td>
<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Description</td>
<td>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
AttendanceCode
</td>
<td>
<asp:TextBox ID="txtRandomCode" runat="server"></asp:TextBox>
<asp:Button ID="btnGenerate0" runat="server" OnClick="GenerateOTP" Text="Generate" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:TextBox ID="txtTechnology" runat="server" Visible="False"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Submit"
OnClick="btnAdd_Click" Width="150px" />
<asp:Button ID="btnClear" runat="server" Text="Clear"
onclick="btnClear_Click" Width="150px" />
</td>
</tr>
</table>
</div>
<br />
<br />
<div>
<table>
<tr>
<td>
<h2>
XML Records</h2>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdxml" runat="server" AutoGenerateColumns="false" BackColor="White"
BorderColor="Black" BorderStyle="None" BorderWidth="1px" CellPadding="1" GridLines="Vertical"
OnSelectedIndexChanged="grdxml_SelectedIndexChanged"
onrowdeleting="grdxml_RowDeleting">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="na">
<ItemTemplate>
<asp:Label ID="lblEmpDesignation" runat="server" Text='<%# Bind("Designation")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CourseID">
<ItemTemplate>
<asp:Label ID="lblEmpEmailID" runat="server" Text='<%# Bind("EmailID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblEmpCity" runat="server" Text='<%# Bind("City")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblEmpCountry" runat="server" Text='<%# Bind("Country")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="na">
<ItemTemplate>
<asp:Label ID="lblEmpTechnology" runat="server" Text='<%# Bind("Technology")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="delete">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="Azure" Font-Bold="True" />
<PagerStyle BackColor="ActiveCaption" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="LightCyan" ForeColor="Black" />
<SelectedRowStyle BackColor="LightSalmon" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
namespace xmlInsertUpdateDelete
{
public partial class XMLAddUpdateDelete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Courses.xml"));
if (ds != null && ds.HasChanges())
{
grdxml.DataSource = ds;
grdxml.DataBind();
}
else
{
grdxml.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text.ToString().Equals("Update Record"))
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Courses.xml"));
int xmlRow = Convert.ToInt32(Convert.ToString(ViewState["gridrow"]));
ds.Tables[0].Rows[xmlRow]["Name"] = txtName.Text;
ds.Tables[0].Rows[xmlRow]["Designation"] = txtDesignation.Text;
ds.Tables[0].Rows[xmlRow]["EmailID"] = txtEmailID.Text;
ds.Tables[0].Rows[xmlRow]["City"] = txtCity.Text;
ds.Tables[0].Rows[xmlRow]["Country"] = txtRandomCode.Text;
ds.Tables[0].Rows[xmlRow]["Technology"] = txtTechnology.Text;
ds.WriteXml(Server.MapPath("~/Courses.xml"));
BindGrid();
}
else
{
XmlDocument xmlEmloyeeDoc = new XmlDocument();
xmlEmloyeeDoc.Load(Server.MapPath("~/Courses.xml"));
XmlElement ParentElement = xmlEmloyeeDoc.CreateElement("Course");
XmlElement ID = xmlEmloyeeDoc.CreateElement("ID");
ID.InnerText = txtID.Text;
XmlElement Name = xmlEmloyeeDoc.CreateElement("Name");
Name.InnerText = txtName.Text;
XmlElement Designation = xmlEmloyeeDoc.CreateElement("Designation");
Designation.InnerText = txtDesignation.Text;
XmlElement EmailID = xmlEmloyeeDoc.CreateElement("EmailID");
EmailID.InnerText = txtEmailID.Text;
XmlElement City = xmlEmloyeeDoc.CreateElement("City");
City.InnerText = txtCity.Text;
XmlElement Country = xmlEmloyeeDoc.CreateElement("Country");
Country.InnerText = txtRandomCode.Text;
XmlElement Technology = xmlEmloyeeDoc.CreateElement("Technology");
Technology.InnerText = txtTechnology.Text;
ParentElement.AppendChild(ID);
ParentElement.AppendChild(Name);
ParentElement.AppendChild(Designation);
ParentElement.AppendChild(EmailID);
ParentElement.AppendChild(City);
ParentElement.AppendChild(Country);
ParentElement.AppendChild(Technology);
xmlEmloyeeDoc.DocumentElement.AppendChild(ParentElement);
xmlEmloyeeDoc.Save(Server.MapPath("~/Courses.xml"));
BindGrid();
}
ClearControl();
}
private void ClearControl()
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtDesignation.Text = string.Empty;
txtEmailID.Text = string.Empty;
txtCity.Text = string.Empty;
txtRandomCode.Text = string.Empty;
txtTechnology.Text = string.Empty;
txtID.Enabled = true;
}
protected void grdxml_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdxml.SelectedRow;
txtID.Text = (row.FindControl("lblEmpId") as Label).Text;
txtName.Text = (row.FindControl("lblEmpName") as Label).Text;
txtDesignation.Text = (row.FindControl("lblEmpDesignation") as Label).Text;
txtEmailID.Text = (row.FindControl("lblEmpEmailID") as Label).Text;
txtCity.Text = (row.FindControl("lblEmpCity") as Label).Text;
txtRandomCode.Text = (row.FindControl("lblEmpCountry") as Label).Text;
txtTechnology.Text = (row.FindControl("lblEmpTechnology") as Label).Text;
ViewState["gridrow"] = row.RowIndex.ToString();
btnAdd.Text = "Update Record";
txtID.Enabled = false;
}
protected void grdxml_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Courses.xml"));
ds.Tables[0].Rows.RemoveAt(e.RowIndex);
ds.WriteXml(Server.MapPath("~/Courses.xml"));
BindGrid();
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearControl();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GenerateOTP(object sender, EventArgs e)
{
{
//string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
string numbers = "1234567890";
string characters = numbers;
//if (rbType.SelectedItem.Value == "1")
//{
//characters += alphabets + small_alphabets + numbers;
//characters += numbers;
//}
//int length = int.Parse(ddlLength.SelectedItem.Value);
int length = 5;
string otp = string.Empty;
for (int i = 0; i < length; i++)
{
string character = string.Empty;
do
{
//int index = new Random().Next(0, characters.Length);
int index = new Random().Next(0, 5);
character = characters.ToCharArray()[index].ToString();
} while (otp.IndexOf(character) != -1);
otp += character;
}
//lblOTP.Text = otp;
txtRandomCode.Text = otp;
}
}
}
}
Since the generation of the page is done server-side before it is displayed to the user regarding the ASP side of things (disregarding any AJAX that is triggered and posted to the page that may be called client-side) you can just provide these instructions in the Page Load method.
If you look at the life cycle
You can see that it would be acceptable for your purpose to initialise the control and set properties such as text in the Page Load method for when the page is created. All you need is for runat="server" to be implied and to access the control from the code behind using it's ID. You can then set its innerHTML to whatever you like or it's .Text property or Value.
The assignment will look something like this:
//Front-end:
<input id="txt" runat="Server" type="text" />
//Code behind:
protected void Page_Load(object sender, EventArgs e)
{
txt.Value = "Bob123";
}
Or this if it's an ASP control:
//In the .aspx:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
//In the .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = SomeMethod();
}
public string SomeMethod()
{
return "Foo";
}

Repeater list is not getting updated in OnItemCommand method

I have a repeater control. In OnItemCommand method of repeater, after doing some operations I am trying to refresh the repeater list so that it could show me the updated list. But somehow repeater list is not updated in method. However when I reload the page then repeater list gets updated with most recent items.
ASPX:
<asp:Label ID="Message1" runat="server" ForeColor="Blue" Text=""></asp:Label>
<div id="ListingAgentsData" class="panel panel-default" style="width: 920px;">
<asp:Repeater ID="rptagentList" runat="server" OnItemCommand="rptagentList_OnItemCommand">
<HeaderTemplate>
<table id="results1" cellpadding="4" cellspacing="1" width="100%">
<tr>
<td>
<strong>AgentID</strong>
</td>
<td>
<strong>Email</strong>
</td>
<td>
<strong>FullName</strong>
</td>
<td>
<strong>Driver License/Passport</strong>
</td>
<td>
<strong>Action</strong>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblDayofweek" runat="server" Text='<%#Eval("AgentID")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblTime" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblCharges" runat="server" Text='<%#Eval("FullName")%>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("DriverLicense")%>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="ibtn" runat="server" Text="Approve" CommandName="Approve" CommandArgument='<%#Eval("AgentID")%>' />
<asp:LinkButton ID="LinkButton1" runat="server" Text="Reject" CommandName="Reject" CommandArgument='<%#Eval("AgentID")%>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
.CS:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] == null)
Response.Redirect("../Login/Default.aspx");
else
{
Init();
}
}
protected void rptagentList_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
try
{
if (e.CommandName == "Approve")
{
int agentId = Convert.ToInt32(e.CommandArgument);
GM gm = new GM();
if (gm.ApproveListingAgent(agentId))
{
Message1.Text = "Listing Agent with ID:"+agentId+" is approved!";
Init();
}
}
else if (e.CommandName == "Reject")
{
}
}
catch (Exception ex)
{
throw ex;
}
}
private void Init()
{
ListingAgent Agent = new ListingAgent();
DataTable dt = Agent.getPendingListingAgents();
if (dt.Rows.Count > 0)
{
rptagentList.DataSource = dt;
rptagentList.DataBind();
}
}
What am I missing?
Please help!

Update MySQL using HyperLink ASP.NET

I store all data in MySQL and display it's some colums in gridview. Gridview's delete button works fine. I would like to edit datas so created HyperLink. it navigates another url and gets values from MySQL DB and sets textboxes, textareas. Everything is fine until this time but I try to edit values in new page it sets old values in DB. How i can solve this problem?
This my Main Page which has gridview and delete button, hyperlink KayitGoruntule.aspx;
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="KayitGoruntule.aspx.cs" Inherits="gop.KayitGoruntule" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.string {
text-align: left;
}
</style>
</head>
<body>
<center><asp:Image ID="Banner" runat="server" ImageUrl="images/logo.png" Height="88px" Width="509px"></asp:Image></center>
<form id="form1" runat="server">
<br />
<div>
<asp:GridView ID="gvMysqlData" runat="server" CssClass="string"
SelectedIndex="0" DataKeyNames="id"
ShowHeaderWhenEmpty="True" OnRowDeleting="gvMysqlData_RowDeleting" Height="95px" Width="492px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="15%">
<ItemTemplate>
<asp:HyperLink ID="hpr1" runat="server" NavigateUrl='<%# string.Format("KayitAyrinti.aspx?id={0}",Eval("id")) %>'>
<img src="images/edit.png" />
</asp:HyperLink>
</ItemTemplate>
<ItemStyle Width="15%" />
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
</form>
</body>
</html>
Navigated Url's page KayitAyrinti.aspx;
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="KayitAyrinti.aspx.cs" Inherits="gop.KayitAyrinti" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style2 {
height: 23px;
width: 217px;
}
.auto-style1 {
height: 23px;
width: 271px;
}
.degistir-button {
background:#7ab752;
margin:1px auto 0px;
text-align:right;
color:#FFF;
/*border:none;
border-top-left-radius:4px;
border-bottom-left-radius:4px;*/
-webkit-transition:background 0.5s;
}
.degistir-button:hover {
background:#DC3F42 #81c356;
}
.kaydet-button {
background:#7ab752;
margin:auto;
margin-right:4px;
margin-left:60px;
text-align:right;
color:#FFF;
/* border:none;
border-top-left-radius:40px;
border-bottom-left-radius:40px;
*/
-webkit-transition:background 0.5s;
}
.kaydet-button:hover {
background:#DC3F42 #81c356;
}
</style>
</head>
<body>
<center><asp:Image ID="Banner" runat="server" ImageUrl="images/logo.png" Height="88px" Width="509px"></asp:Image></center>
<form id="register" runat="server">
<br />
<div>
<table align="center">
<tr>
<td class="auto-style1" >
<asp:Label ID="lbl_ayrintiYetkiliAdSoyad" runat="server" Text="Yetkili Adı Soyad :" Font-Bold="True" Font-Names="Book Antiqua" ></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiYetkiliAdSoyad_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ayrintiGorusmeYapilanOkul" runat="server" Text="Görüşme Yapılan Okul :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:RadioButtonList ID="RadioButtonList_ayrintiGorusmeYapilanOkul" runat="server" Width="174px">
<asp:ListItem>Seyrantepe Şube 1</asp:ListItem>
<asp:ListItem>Seyrantepe Şube 2</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ayrintiveliAdSoyad" runat="server" Text="Veli Adı Soyadı :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiVeliAdiSoyadi_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_veliTel" runat="server" Text="Veli Telefon Numarası :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiVeliTel_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ikametAdres" runat="server" Text="İkamet Adresi :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<textarea id="ayrintiIkametAdres_txt" rows="5" cols="26" runat="server"></textarea>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ogrenciAdSoyad" runat="server" Text="Öğrenci Adı Soyadı :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiOgrenciAdSoyad_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ogrenciTel" runat="server" Text="Öğrenci Telefon Numarası :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiOgrenciTel_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_ilgilendigiBolum" runat="server" Text="İlgilendiği Bölüm :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:RadioButtonList ID="RadioButtonList_ayrintiIlgilendigiBolum" runat="server" Width="174px">
<asp:ListItem>Hemşire Yardımcılığı</asp:ListItem>
<asp:ListItem>Sağlık Bakım Teknisyenliği</asp:ListItem>
<asp:ListItem>Anadolu Lisesi</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_verilenFiyat" runat="server" Text="Verilen Fiyat :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiVerilenFiyat_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_gorusmeSonucu" runat="server" Text="Görüşme Sonucu :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="ayrintiGorusmeSonucu_txt" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="lbl_gorusmeNotlari" runat="server" Text="Görüşme Notları :" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<textarea id="ayrintiGorusmeNotlari_txt" rows="5" cols="26" runat="server"></textarea>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="Label1" runat="server" Text="" Font-Bold="True" Font-Names="Book Antiqua"></asp:Label>
</td>
<td class="auto-style2">
<asp:button id="degistir" runat="server" text="Değiştir" class="degistir-button" OnClick="degistir_Click"/>
<asp:Button ID="kaydet" runat="server" Text="Kaydet" CssClass="kaydet-button" OnClick="kaydet_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
This class is which shows values and try to update with degistir_Click,
KayitAyrinti.aspx.cs;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace gop
{
public partial class KayitAyrinti : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["kullanici"] != null)
{
Response.Write("Hoşgeldiniz..." + Session["kullanici"]);
Response.Redirect("KayitAyrinti.aspx");
}
else
{
// Response.Write("Giriş Yapınız.");
}
string connectionString = "xxx;Database=xxx;Uid=xxxx;Pwd=xxx;";
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
string[] keys = Request.QueryString.GetValues("id");
String id = keys[0];
MySqlCommand cmd = new MySqlCommand("select id, yetkiliAdSoyad,gorusmeYapilanOkul,veliAdSoyad, veliTel, ikametAdres, ogrenciAdSoyad, ogrenciTel, ilgilendigiBolum,verilenFiyat,gorusmeSonucu,gorusmeNotlari from Kayitlar where id=" + id + "", cn);
try
{
cn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ayrintiYetkiliAdSoyad_txt.Text = (reader["yetkiliAdSoyad"].ToString());
RadioButtonList_ayrintiIlgilendigiBolum.SelectedValue = (reader["gorusmeYapilanOkul"].ToString());
ayrintiVeliAdiSoyadi_txt.Text = (reader["veliAdSoyad"].ToString());
ayrintiVeliTel_txt.Text = (reader["veliTel"].ToString());
ayrintiIkametAdres_txt.InnerText = (reader["ikametAdres"].ToString());
ayrintiOgrenciAdSoyad_txt.Text= (reader["ogrenciAdSoyad"].ToString());
ayrintiOgrenciTel_txt.Text = (reader["ogrenciTel"].ToString());
RadioButtonList_ayrintiIlgilendigiBolum.SelectedValue= (reader["ilgilendigiBolum"].ToString());
ayrintiVerilenFiyat_txt.Text= (reader["verilenFiyat"].ToString());
ayrintiGorusmeSonucu_txt.Text= (reader["gorusmeSonucu"].ToString());
ayrintiGorusmeNotlari_txt.InnerText = (reader["gorusmeNotlari"].ToString());
}
}
}
catch (Exception ex)
{
}
}
}
protected void degistir_Click(object sender, EventArgs e)
{
string connectionString = "Server=xxx;Database=xxx;Uid=xxx;Pwd=xxx;";
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
string[] keys = Request.QueryString.GetValues("id");
String id = keys[0];
cn.Open();
MySqlCommand komut = new MySqlCommand("UPDATE Kayitlar SET yetkiliAdSoyad=#ayrintiYetkiliAdSoyad, gorusmeYapilanOkul = #ayrintiGorusmeYapilanOkul,"+
" veliAdSoyad = #ayrintiVeliAdSoyad ,veliTel = #ayrintiVeliTel,ikametAdres = #ayrintiIkametAdres ,ogrenciAdSoyad = #ayrintiOgrenciAdSoyad, " +
"ogrenciTel=#ayrintiOgrenciTel,ilgilendigiBolum = #ayrintiIlgilendigiBolum,verilenFiyat=#ayrintiVerilenFiyat,gorusmeSonucu=#ayrintiGorusmeSonucu,gorusmeNotlari=#ayrintiGorusmeNotlari", cn);
komut.Parameters.AddWithValue("#ayrintiYetkiliAdSoyad", ayrintiYetkiliAdSoyad_txt.Text);
komut.Parameters.AddWithValue("#ayrintiGorusmeYapilanOkul", RadioButtonList_ayrintiGorusmeYapilanOkul.SelectedValue);
komut.Parameters.AddWithValue("#ayrintiVeliAdSoyad", ayrintiVeliAdiSoyadi_txt.Text);
komut.Parameters.AddWithValue("#ayrintiVeliTel", ayrintiVeliTel_txt.Text);
komut.Parameters.AddWithValue("#ayrintiIkametAdres", ayrintiIkametAdres_txt.InnerText);
komut.Parameters.AddWithValue("#ayrintiOgrenciAdSoyad", ayrintiOgrenciAdSoyad_txt.Text);
komut.Parameters.AddWithValue("#ayrintiOgrenciTel", ayrintiOgrenciTel_txt.Text);
komut.Parameters.AddWithValue("#ayrintiIlgilendigiBolum", RadioButtonList_ayrintiIlgilendigiBolum.SelectedValue);
komut.Parameters.AddWithValue("#ayrintiVerilenFiyat", ayrintiVerilenFiyat_txt.Text);
komut.Parameters.AddWithValue("#ayrintiGorusmeSonucu", ayrintiGorusmeSonucu_txt.Text);
komut.Parameters.AddWithValue("#ayrintiGorusmeNotlari", ayrintiGorusmeNotlari_txt.InnerText);
komut.ExecuteNonQuery();
Response.Redirect("KayitGoruntule.aspx");
komut.Dispose();
}
}
protected void kaydet_Click(object sender, EventArgs e)
{
}
}
}
The textboxes on your form are being populated with their database defaults in the Page_Load event. This is fine the first time through; however, when you click your 'degistir' button, a "postback" occurs, and Page_Load fires again and repopulates those defaults, losing whatever changes were submitted. Keep in mind that Page_Load fires before any control click events.
To fix this, you need to check for IsPostback in Page_Load to prevent your loader from firing on the update. If IsPostback is true, inhibit the load of the defaults from your database. This, in turn, should allow the update to occur with the updated data provided on your form. Something along these lines:
// code snipped...
if (Session["kullanici"] != null)
{
Response.Write("Hoşgeldiniz..." + Session["kullanici"]);
Response.Redirect("KayitAyrinti.aspx");
}
else
{
// Response.Write("Giriş Yapınız.");
}
if (!IsPostback) // <-- Add this check
{
string connectionString = "xxx;Database=xxx;Uid=xxxx;Pwd=xxx;";
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
string[] keys = Request.QueryString.GetValues("id");
/// rest of code snipped
Also, be sure to modify your UPDATE statement to include a WHERE clause that limits the UPDATE to only that record with the desired ID. As it is, ALL your records will be updated!

How can I open another page when pressing the Edit button on a gridview?

I have a Gridview control in asp.net with C#.
In my application when I press the edit button from Gridview I need to open the information in another window. At this moment I use 'Response.Redirect("..")' but it opens in the same window.
I've tried:
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
outputGridView.EditIndex = e.NewEditIndex;
GridViewRow row = outputGridView.Rows[outputGridView.EditIndex];
string url = "http://localhost/MyPage.aspx";
Response.Write("<script>");
Response.Write("window.open('" + url + "')");
Response.Write("<" + "/script>")
e.Cancel = true;
}
But with no luck.
What's the best way to do this?
Try this
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
outputGridView.EditIndex = e.NewEditIndex;
GridViewRow row = outputGridView.Rows[outputGridView.EditIndex];
string url = "http://localhost/MyPage.aspx";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<script type='text/javascript'>");
sb.AppendLine("window.open('" + url + "')");
sb.AppendLine("<" + "/script>");
ClientScript.RegisterStartupScript(this.GetType(), "myjs", sb.ToString(), false);
//or if the gridview is inside an updatepanel do the code given below
//ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "myjs", sb.ToString(), false);
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception err)
{
//handle error here
//Elmah.ErrorSignal.FromCurrentContext().Raise(err);
}
}
As I have commented in the code above, if you are using ScriptManager, uncomment and use this
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "myjs", sb.ToString(), false);
I have tested it and its working.
This code will open the window in new window. for this you need to use the ScriptManager
string BrowserSettings = "status=no,toolbar=no,menubar=no,location=no,resizable=no,"+
"titlebar=no, addressbar=no, width=600 ,height=750";
string URL = "http://localhost/MyPage.aspx";
string scriptText = "window.open('" + URL + "','_blank','" + BrowserSettings + "');";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ClientScript1", scriptText, true);
ASPX: Create a gridview like this
<asp:GridView runat="server" AllowPaging="True" AutoGenerateColumns="False" ID="gvSticker"
Width="100%" EmptyDataText="No sticker found for this Fisher. Click on add to Add a new sticker."
HorizontalAlign="Left" ShowFooter="True" ShowHeaderWhenEmpty="True" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" PageSize="3"
OnRowDataBound="gvSticker_RowDataBound" OnPageIndexChanging="gvSticker_PageIndexChanging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<table style="width: 100%">
<tr align="left">
<td style="width: 15%">
Sticker Year
</td>
<td style="width: 15%">
Sticker Number
</td>
<td style="width: 15%">
Issue Date
</td>
<td style="width: 35%">
Issue Type
</td>
<td style="width: 20%">
Status
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table style="width: 100%">
<tr align="left">
<td style="width: 15%">
<%# Eval("YearOfIssue")%>
</td>
<td style="width: 15%">
<asp:HyperLink ID="hlStickerNumber" runat="server" Text='<%#Eval("StickerNumber")%>' Style="cursor: hand; text-decoration:underline"></asp:HyperLink>
</td>
<td style="width: 15%">
<%# Eval("DateOfIssue", "{0:MM/dd/yyyy}")%>
</td>
<td style="width: 35%">
<%# Eval("RegistrationType")%>
</td>
<td style="width: 20%">
<asp:Label ID="lblStickerStatus" runat="server" Text='<%# Eval("StickerStatus")%>'></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle HorizontalAlign="Left" BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
In data bound event add the code.
protected void gvSticker_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (Session["FisherId"] != null)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblStatus = (Label)e.Row.FindControl("lblStickerStatus");
if (e.Row.RowIndex == 0)
{
if (lblStatus.Text.Contains("Active"))
{
btnAddSticker.Enabled = false;
HyperLink hlStickerNum = (HyperLink)e.Row.FindControl("hlStickerNumber");
if (!string.IsNullOrEmpty(hlStickerNum.Text.Trim()))
{
string urlWithParameters =
"Stickers.aspx?StickerId=" +
hlStickerNum.Text;
hlStickerNum.Attributes.Add("OnClick",
"popWinNote('" + urlWithParameters +
"')");
}
}
else
{
btnAddSticker.Enabled = true;
btnVoidSticker.Enabled = true;
}
}
}
}
else
{
btnAddSticker.Enabled = true;
btnVoidSticker.Enabled = true;
}
}
And in aspx page add a function in script tag PopWinNote to open a show modal dialog if you need a small window. This code is not actually your required code but might give you idea regarding the implementation of logic
Instead of writing directly to the response stream try this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenNewWindow", "window.open(...)", true);

Categories

Resources