ASP.net 4.6 c# Set text when page opens - c#

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";
}

Related

Deleting item from ListView

I am trying to do an ASP.NET application. I am using a DataSet which I set as DataSource in a ListView that I have in my .aspx file. The problem is when I click the delete button nothing seems to happen, but when I refresh the browser I get an error message as follows:
"To display the webpage again, the web browser needs to resend the
information you've previosly submitted."
I have really tried to figure out what I am doing wrong or what might cause this. This is my C# code:
namespace WebApplication1
{
public partial class _Default : Page
{
DataSet orderDetails;
protected void Page_Load(object sender, EventArgs e)
{
Message.Text = "";
string orderPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orders.xml";
string orderSchemaPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orderschema.xsd";
XDocument document = XDocument.Load(orderPath);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(orderSchemaPath));
bool errors = false;
document.Validate(schemas, (o, err) =>
{
System.Diagnostics.Debug.WriteLine("Validation error: {0}", err.Message);
errors = true;
});
if (!errors)
{
System.Diagnostics.Debug.WriteLine("XML document successfully validated.");
try
{
orderDetails = new DataSet();
orderDetails.ReadXml(orderPath);
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex);
}
}
else
{
System.Diagnostics.Debug.WriteLine("XML document does not validate.");
}
System.Diagnostics.Debug.WriteLine("Page_load done");
}
void BindData()
{
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
//Call databind method in your prerender event
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void OrderListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
listViewOrders.DeleteItem(e.Item.DataItemIndex);
BindData();
}
}
protected void OrdersListView_ItemDeleted(object sender, ListViewDeletedEventArgs e)
{
//Check if an exception occurred to display an error message.
if (e.Exception != null)
{
Message.Text = "An exception occurred deleting the contact.";
e.ExceptionHandled = true;
}
else
{
// Clear the selected index.
listViewOrders.SelectedIndex = -1;
}
}
protected void OrdersListView_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
}
}
}
And this is the ListView that I have in my .aspx file:
<asp:ListView ID="listViewOrders"
DataKeyNames="orderid"
runat="server"
OnItemDeleting="OrdersListView_OnItemDeleting"
OnItemCommand="OrderListView_ItemCommand">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" id="tblProducts">
<tr runat="server">
<th runat="server">Order person</th>
<th runat="server">Order ID</th>
<th runat="server">Delete</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="Server" Text='<%#Eval("orderperson") %>' />
</td>
<td valign="top">
<asp:Label ID="LastNameLabel" runat="Server" Text='<%#Eval("orderid") %>' />
</td>
<td>
<asp:LinkButton ID="DeleteButton" runat="Server" class="glyphicon glyphicon-remove" CommandName="Delete" CommandArgument="X" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr style="background-color: #ADD8E6">
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%#Bind("orderperson") %>'
MaxLength="50" /><br />
</td>
<td>
<asp:TextBox ID="LastNameTextBox" runat="server" Text='<%#Bind("orderid") %>'
MaxLength="50" /><br />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
When you are using the listView Commands you have to update the panels.
Place your listView inside a asp:panel like this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
... your list View Code
</ContentTemplate>
</asp:UpdatePanel>
And after the DataBind you have to update the panel by
UpdatePanel1.Update();

ASP.Net gridview not refreshing when used with Ajaxtoolkit Upload control

I have an asp.net web page that allows for manual entry of a record, or an import from an excel spreadsheet to import multiple records.
After the records are added by either process, they display in a Gridview control (bound to a SQLDataReader). This allows the user to edit or delete a record before submitting the entire dataset for processing.
I'm using an Ajax Toolkit AsyncFileUpload control to handle the import. The UploadedComplete c# function runs properly and the records are inserted into the SQL table. The code then calls my DataBindGrid() function to refresh the grid. I can step through the code and see that every line is executing, however, it seems like it never actually finishes, even though stepping through debugging completes.
Two steps are not actually completing, the grid refresh and the label display that indicates to the user that the process is complete.
For testing purposes, I've added a linkButton that calls the BindDataGrid() when clicked. This works to refresh the grid and to also display the status label. It's not a permanent solution, it would be too risky to have a user remember to refresh, they are likely to think that all their records have already been submitted.
At first I thought my problem was trying to do more inside the UploadComplete function then just upload the file (I'm reading the Excel file that was uploaded), so I broke out the code and added a button for the user to click to initiate the actual data processing. This failed because although I could see the file name being saved into a hidden form during the UploadComplete function, when I went to read that hidden field, the data was no longer in it. I'm not loosing the values in any of the other hidden fields.
I've been researching this for 3 days and I'm really stuck. I'm assuming that I am having a problem with postback, but have no clue at this point.
Here is my code:
<%# Page Title="" Language="C#" MasterPageFile="~/WTIMS.Master" AutoEventWireup="true" CodeBehind="OptionsEntry.aspx.cs" Inherits="WTIMS_OptionsEntry.Pages.OptionsEntry" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" language=javascript>
function uploadError(sender, args) {
var errMsg = args.get_errorMessage();
updateUploadStatus("error", errMsg);
}
function updateUploadStatus(status, message) {
var uploadStatLabel = document.getElementById('ContentPlaceHolder1_lblError');
uploadStatLabel.innerText = message;
if (status == "error") {
uploadStatLabel.className = "LabelErrorMessage";
}
else {
uploadStatLabel.className = "LabelScucessMessage";
}
}
function startUpload(sender, args) {
var fileName = args.get_fileName();
var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
if (fileExt == "xlsx") {
return true;
}
else {
var err = new Error()
err.name = "Upload Error";
err.message = "Only .xlsx files can be uploaded";
throw (err);
return false;
}
}
function uploadComplete(sender, args) {
var rowCount = sender.rowCount;
}
</script>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<table width = 100% cellpadding=1>
<tr>
<td colspan=2>
<asp:Label ID="Label19" runat="server" Text="Upload batch" CssClass=LabelInfo></asp:Label>
</td>
</tr>
<tr>
<td width=50%>
<asp:AsyncFileUpload
ID="AsyncFileUpload1"
Width=400px
ThrobberID=Throbber
UploaderStyle=Modern
CompleteBackColor = "#9BCD9B"
ErrorBackColor="#D44942"
OnClientUploadStarted="startUpload"
OnClientUploadError="uploadError"
OnClientUploadComplete="uploadComplete"
OnUploadedComplete=AsyncFileUpload1_UploadedComplete
OnUploadedFileError=AsyncFileUpload1_UploadedFileError
UploadingBackColor=AliceBlue
runat="server" />
<asp:Label ID="Throbber" runat="server" Text="Label" Style="display:none">
<img src="../../images/LoadingWait.gif" alt="loading" />
</asp:Label>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="lkbRefresh" CssClass=linkButton
Text = "Records Upload, Click to View" runat="server"
onclick="lkbRefresh_Click">LinkButton</asp:LinkButton>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblError" runat="server" Text="" CssClass="LabelErrorMessage"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblStatus" runat="server" Text="" CssClass=LabelFormLabel></asp:Label>
</td>
</tr>
</table>
asp.net code for Grid:
<table>
<tr>
<td>
<asp:Label ID="Label18" runat="server" Text="Pending Options" CssClass=LabelInfo></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit Pending Options"
CssClass=button onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdOptions"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="OptionRecordID"
EmptyDataText="You Have no pending Options"
onrowdatabound="grdOptions_RowDataBound">
<FooterStyle CssClass="FooterStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<RowStyle CssClass="RowStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<PagerStyle CssClass="PagerStyle" />
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton ID="lkbSave" runat="server" Text= "Save" CssClass=linkButton onclick="lkbSave_Click"></asp:LinkButton>
<asp:LinkButton ID="lkbCancek" runat="server" Text="Cancel" CssClass=linkButton onclick="lkbCancel_Click"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lkbEdit" runat="server" Text= "Edit" CssClass=linkButton onclick="lkbEdit_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OptionRecordID" InsertVisible="False"
SortExpression="OptionRecordID" Visible="False">
<EditItemTemplate>
<asp:Label ID="lblOptionIDEdit" runat="server" Text='<%# Eval("OptionRecordID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblOptionID" runat="server" Text='<%# Bind("OptionRecordID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SecurityID" SortExpression="SecurityID">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("SecurityID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Symbol" SortExpression="Symbol">
<EditItemTemplate>
<asp:TextBox ID="txtSymbolEdit" Width=75px runat="server" Text='<%# Bind("Symbol") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Symbol") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Call/Put" SortExpression="CallPut">
<EditItemTemplate>
<asp:DropDownList ID="ddlPutCallEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("CallPut") %>'>
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text ="Put" Value = "Put"></asp:ListItem>
<asp:ListItem Text ="Call" Value = "Call"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("CallPut") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buy Write" SortExpression="BuyWrite">
<EditItemTemplate>
<asp:DropDownList ID="ddlWtriteBuyEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("BuyWrite") %>'>
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text ="Buy" Value = "Buy"></asp:ListItem>
<asp:ListItem Text ="Write" Value = "Write"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Bind("BuyWrite") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<EditItemTemplate>
<asp:TextBox ID="txtPriceEdit" Width=75px runat="server" Text='<%# Bind("Price") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiration Date" SortExpression="ExpirationDate">
<EditItemTemplate>
<asp:TextBox ID="txtExpirationDateEdit" Width=100px runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescriptionEdit" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UploadStatus" SortExpression="UploadStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Bind("UploadStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lkbDelete" runat="server" CssClass=linkButton Text="Delete" onclick="lkbDelete_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
C# Code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
strFileName = Server.MapPath("~/Files/" + this.hdnSessionID.Value + "_uploaded.xlsx");
string strUploadFileName = AsyncFileUpload1.FileName.ToString();
InsertData.InsertLogMessage("File to upload: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
this.hdnUploadFileName.Value = strFileName;
AsyncFileUpload1.SaveAs(strFileName);
InsertData.InsertLogMessage("File saved: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
UploadData(strFileName);
DataBindGrid();
}
protected void UploadData(string strUploadFileName)
{ //process the file that was uploaded
try
{
InsertData.InsertLogMessage("Starting Upload", "OptionsEntry", this.hdnUserID.Value);
int i = 0;
// string strFileName = this.hdnUploadFileName.Value;
FileStream myStream = File.Open(strUploadFileName, FileMode.Open, FileAccess.Read);
IExcelDataReader myReader = ExcelReaderFactory.CreateOpenXmlReader(myStream);
myReader.IsFirstRowAsColumnNames = true;
DataSet result = myReader.AsDataSet();
foreach (DataTable dt in result.Tables)
{
foreach (DataRow dr in dt.Rows)
{
Boolean blnIsValid = true;
//code here to loop through file and insert records
InsertData.InsertOptionEntryFormData(strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, this.hdnUserID.Value, strTicker, strStatus);
i = i + 1;
}
}
this.lblStatus.Text = i + " records have been imported to the pending table. Please review and correct any errors before submitting.";
InsertData.InsertLogMessage( i + " records have been imported", "OptionsEntry", this.hdnUserID.Value);
DataBindGrid();
}
catch (Exception ex)
{
InsertData.InsertLogMessage("An error occured: " + ex.Message, "OptionsEntry", this.hdnUserID.Value);
this.lblStatus.Text = "There was a problem importing the data, please check the file and try again.";
}
}
protected void DataBindGrid()
{
this.grdOptions.DataSource = GetData.GetOptionEntryFormData(this.hdnUserID.Value);
this.grdOptions.DataBind();
}
Any suggestions would be greatly appreciated!
Christine
EDIT - Code for the grdOptions
protected void grdOptions_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblStatus = (Label)e.Row.Cells[9].Controls[1];
if (lblStatus.Text == "Invalid")
{
e.Row.CssClass = "RowError";
}
else
{
if (e.Row.RowState == DataControlRowState.Alternate)
{
e.Row.CssClass = "AlternatingRowStyle";
}
else
{
e.Row.CssClass = "RowStyle";
}
}
}
}
#region Grid Link Actions
protected void lkbSave_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Visible = false;
ClearFormColor();
Boolean blnIsValid = true; //start off assuming everthing is valid
//get the row that we are sitting on
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
//get the data we need
Label lblOptionIDEdit = (Label)row.FindControl("lblOptionIDEdit");
int intOptionIDEdit = int.Parse(lblOptionIDEdit.Text);
TextBox txtSymbolEdit = (TextBox)row.FindControl("txtSymbolEdit");
strSymbol = txtSymbolEdit.Text;
if(!ValidateSymbol())
{
ToggleTextBoxColor(false,txtSymbolEdit);
blnIsValid = false;
}
DropDownList ddlPutCallEdit = (DropDownList)row.FindControl("ddlPutCallEdit");
strCallPut = ddlPutCallEdit.SelectedValue;
if(!ValidateCallPut())
{
ToggleDropDownColor(false,ddlPutCallEdit);
blnIsValid = false;
}
DropDownList ddlWtriteBuyEdit = (DropDownList)row.FindControl("ddlWtriteBuyEdit");
strBuyWrite = ddlWtriteBuyEdit.SelectedValue;
if(!ValidateBuyWrite())
{
ToggleDropDownColor(false,ddlWtriteBuyEdit);
blnIsValid= false;
}
TextBox txtPriceEdit = (TextBox)row.FindControl("txtPriceEdit");
strPrice = txtPriceEdit.Text;
if(!ValidateStrikePrice())
{
ToggleTextBoxColor(false,txtPriceEdit);
blnIsValid= false;
}
TextBox txtExpirationDateEdit = (TextBox)row.FindControl("txtExpirationDateEdit");
strExpirationDate = txtExpirationDateEdit.Text;
if(!ValidateExpirationDate())
{
ToggleTextBoxColor(false,txtExpirationDateEdit);
blnIsValid = false;
}
TextBox txtDescriptionEdit = (TextBox)row.FindControl("txtDescriptionEdit");
strDescription = txtDescriptionEdit.Text;
if(!blnIsValid)
{
this.lblErrorMessage.Text = "Please corrext the data highlighted in yellow";
this.lblErrorMessage.Visible= true;
return;
}
FormatTicker();
//update the data
UpdateData.UpdateOptionEntryFormData(intOptionIDEdit, strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, strTicker, "Manual");
//refresh the grid
this.grdOptions.EditIndex = -1;
DataBindGrid();
}
protected void lkbEdit_Click(object sender, EventArgs e)
{
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
int intIndex = row.RowIndex;
this.grdOptions.EditIndex = intIndex;
DataBindGrid();
}
protected void lkbDelete_Click(object sender, EventArgs e)
{
//get the row that we are sitting on
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
//get the data we need
Label lblRecordID = (Label)row.FindControl("lblOptionID");
int intRecordID = int.Parse(lblRecordID.Text);
//delete the record
DeleteData.DeleteOption(intRecordID);
//refresh the grid
DataBindGrid();
}
protected void lkbCancel_Click(object sender, EventArgs e)
{
this.grdOptions.EditIndex = -1;
}
#endregion

PostBack from a link in Grid within UpdatePanel

I have a grid and few textboxes within an UpdatePanel. On selecting a paricular row the textboxes are filled using JS. UpdatePanel was introduced as one textbox was filled using a method in the code.
There is also a link in grid row which opens a pop-up(also filled from code behind).
After using UpdatePanel the link is not working(assuming because of no full post back).
I tried using UpdateMode="Conditional" property and registering Link control for PostBAck control.
But still it is not working:
Code
<asp:UpdatePanel ID="Update" runat="server" Up>
<ContentTemplate>
<table width="100%">
<tr>
<td>
<asp:GridView ID="gvSession" BorderColor="#ffcc00" RowStyle-BorderColor="#ffcc00"
AutoGenerateColumns="False" Font-Names="Verdana" DataKeyNames="SessionId" runat="server"
RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px" GridLines="Both" Width="100%"
OnRowCreated="gvSession_RowCreated" OnDataBound="gvSession_DataBound">
<RowStyle CssClass="dbGrid_Table_row" />
<HeaderStyle CssClass="dbGrid_Table_Header" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbSelect" onclick="javascript:CheckOtherIsCheckedByGVIDMore(this);"
runat="server" OnCheckedChanged="rbSelect_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Session Name">
<ItemTemplate>
<asp:Label ID="lblSessionName" Text='<%# Eval("SessionName") %>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="16%"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:LinkButton ID="lbPreview" Text="Preview" CommandName="Preview" AutoPostBack="true"
CommandArgument='<%# Eval("SessionId") + ";" + Eval("TrainingTypeName") %>'
runat="server" OnClick="lbPreview_Click"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="10%"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<table id="Table2" runat="server" width="100%">
<tr>
<td colspan="2" align="center" style="text-align: center">
<asp:TextBox ID="txtSessionDtl" runat="server" Font-Size="Small" Style="text-align: center"
ForeColor="Black" Wrap="true" Height="20px" Width="95%" BorderStyle="None"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 12%">
<asp:Label ID="Label9" CssClass="label" runat="server">Upload File : </asp:Label>
</td>
<td>
<asp:TextBox ID="txtFilePath" Enabled="false" BorderStyle="Solid" BorderColor="Black"
runat="server" Width="741px"></asp:TextBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
FOr Link click:
protected void lbPreview_Click(object sender, EventArgs e)
{
try
{
LinkButton link = (LinkButton)sender;
GridViewRow gv = (GridViewRow)(link.Parent.Parent);
LinkButton linkPreview = (LinkButton)gv.FindControl("lbPreview");
string[] arg = new string[2];
arg = linkPreview.CommandArgument.ToString().Split(';');
string strSessionId = arg[0];
string strTrgType = arg[1];
string mailContent = GenerateNominationMailer(strSessionId, strTrgType);
hidMailContent.Value = mailContent;
string mailContent1 = mailContent.Replace(System.Environment.NewLine, "");
string myScript = "<SCRIPT LANGUAGE='javascript'>";
myScript = myScript + " my_window = window.open('', '', 'status=1,width=1000,height=800,scrollbars=yes');";
myScript = myScript + " my_window.document.write(\"" + mailContent1.Replace("\"", "'") + "\");";
myScript = myScript + " my_window.document.close();";
myScript = myScript + " </script>";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Nomination Mailer", myScript,false);
}
catch (Exception ex)
{
AlnErrorHandler.HandleError(ex);
}
}
For registering control:
protected void gvSession_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow grdrow in gvSession.Rows)
{
LinkButton Preview = (LinkButton)grdrow.FindControl("lbPreview");
ScriptManager current = ScriptManager.GetCurrent(Page);
if (current != null)
current.RegisterPostBackControl(Preview);
}
}
enter code here
set trigger for your event. put this at end of ContentTemplate
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lbPreview" EventName="Click" />
</Triggers>
Replace your old event with this
protected void gvSession_DataBound(object sender, GridViewRowEventArgs e)
{
LinkButton Preview = e.Row.FindControl("lbPreview") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(Preview);
}
and assign gvSession_DataBound event in GridView as DataBound event

How to refer to a TextBox in a datalist of the same row of the Button?

I want button in the datalist OnClick gets text from both textboxes on the same row of the button.. how can i refer to that using C# keeping in mind that I want to use my own stored procedures and functions "OnClicking" buttons without using SqlDataSource Control
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table class="auto-style2">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("UDI") %>'></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("describtion") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Modify" CommandArgument='<%# Eval("UDI") %>' OnCommand="Button2_Command" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and here is the code behind
AdminControlEntities db = new AdminControlEntities();
var x=db.sp_GetAllProducts(); //Stored procedure that returns a selection of data
DataList1.DataSource = x.ToList();
DataList1.DataBind();
till here i get my data viewed correctly, I need to Update using my own stored procedure in this example from TextBox1 and TextBox2 to the Label1 ID
ADD OnItemCommand to your mark up
<asp:DataList ID="DataList1" runat="server" OnItemCommand="Modify_ItemCommand" >
Then on Code Behind:
protected void Modify_ItemCommand(object source, DataListCommandEventArgs e)
    {
 
        /* select the row index */
        int index = Convert.ToInt32(e.Item.ItemIndex);
 
        /*To get and Textbox of selected row*/
        TextBox txtbx = (TextBox)e.Item.FindControl("TextBox1");
 
        /* Assigning Value to your textbox */
        txtbx.Text = "What ever you want here";
 
    }
You can declare the button using the property CommandName and then use the ItemCommand event controller.
Source: http://msdn.microsoft.com/es-es/library/es4e4e0e(v=vs.100).aspx
Here, a working example (Note that I'm using an UpdatePanel. Due the content of the page is going to be change, if you do not use it you will get a server error. More info here):
Test.aspx
<asp:UpdatePanel ID="upDataList1" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="lUID" runat="server" Text='<%# Eval("UID") %>' />
</td>
<td>
<asp:TextBox ID="tbName" runat="server" Text='<%# Eval("name") %>' />
</td>
<td>
<asp:TextBox ID="tbDescription" runat="server" Text='<%# Eval("description") %>' />
</td>
<td>
<asp:Button ID="bModify" runat="server" Text="Modify" CommandName="Modify" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
Test.aspx.cs
public partial class Test : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
var x = db.sp_GetAllProducts();
DataList1.DataSource = x;
DataList1.DataBind();
}
}
protected void DataList1_ItemCommand(Object sender, DataListCommandEventArgs e) {
String a = ((TextBox) e.Item.FindControl("tbName")).Text;
String b = ((TextBox) e.Item.FindControl("tbDescription")).Text;
((Label) e.Item.FindControl("lUID")).Text = a + " " + b;
}
}
public class db {
public String UID { get; set; }
public String name { get; set; }
public String description { get; set; }
public db(String UID, String name, String description) {
this.UID = UID;
this.name = name;
this.description = description;
}
public static List<db> sp_GetAllProducts() {
List<db> list = new List<db>();
list.Add(new db("1", "1a", "1b"));
list.Add(new db("2", "2a", "2b"));
list.Add(new db("3", "3a", "3b"));
list.Add(new db("4", "4a", "4b"));
list.Add(new db("5", "5a", "5b"));
list.Add(new db("6", "6a", "6b"));
return list;
}
}

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

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.

Categories

Resources