I've got a web application that has a page full of batch files which the user can run, view the output, and send input. My problem occurs when the process hits something which causes it to pause, such as a pause, or a question that requires the user to press Y or N to continue. We'll go with pause for the purposes of this question.
This is my batch file:
pause
When run in windows, I get the output displayed on my screen "Press any key to continue...", I press enter, and it exits. But when my app runs this batch file, I dont get any output, but I know what it's waiting for so I press enter, and only then do I see the output "Press any key to continue...".
I've created a simplified version of my code in a console app, and the same thing happens, I get a blank screen, I press enter, and then I see "Press any key to continue..."
Any idea how I go about getting this line of output BEFORE I am required to press the key?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace BatchCaller
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = #"C:\Projects\BatchCaller\BatchCaller\Test2.bat",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
Process proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.BeginOutputReadLine();
// Problem is not here, ignore this, just my temporary input method.
// Problem still occurs when these two lines are removed.
string inputText = Console.ReadLine();
proc.StandardInput.WriteLine(inputText);
proc.WaitForExit();
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// This method doesnt get called for output: "Press any key to continue..."
// Why?
if (e.Data != null)
Console.WriteLine(e.Data);
}
}
}
Just checked and I noticed that pause doesn't return to the next line of text until you press the key. That's probably why it's not displaying, since your code is looking for a line return.
Rather than using ReadLine(), try seeing if there's one that will show all the characters as they're printed.
(^that should solve your problem by giving you a more real-time view of what's going on inside)
I'd have thought you'd need to move your:
string inputText = Console.ReadLine();
proc.StandardInput.WriteLine(inputText);
into the OutputDataReceived handler.
Then in your main, call proc.WaitForExit() and with a bit of luck (I haven't tested this) the following should happen:
proc's output buffer is flushed
your OutputDataReceived handler is executed
Console.Write with proc's stdout
Console.Read and send input to proc's stdin
proc exits
I realised it wasn't reading the last line because the data received event was only being triggered after there was a whole line of output, but when it pauses or asks a question, the cursor is still on the same line. A new thread that continuously checked the output stream was the solution to this small problem.
I also managed to solve my whole problem so that now what I've got when I run a script close ly resembles a command prompt window.
Here's a very basic summary of how it works:
I start a new process that runs a batch file. At the same time I start a new thread that continuously loops asking the process for more output, and storing that output in a queue. My .NET timer continuously checks the queue for text, and outputs it into my ajax panel. I use a text box and ajax to input text into the process input and into my ajax panel. I also needed a lot of javascript and I had to use session variables to make it run smoothly.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Scripts.aspx.cs" Inherits="MITool.Scripts" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" language="javascript">
var script = '';
function ShowScriptModal() {
$('#overlay').css({ width: $(document).width(), height: $(document).height(), 'display': 'block' }).animate({ opacity: 0.85 }, 0, function () { $('#scriptModal').show(); });
}
function ScriptInputKeypress(e) {
if (e.keyCode == 13) {
ScriptInput();
}
}
function ScriptInput() {
var txtInput = document.getElementById("txtInput");
var input = txtInput.value;
var hiddenInput = document.getElementById("hiddenInput");
if (input == '')
return;
hiddenInput.value = input;
txtInput.value = '';
}
function CheckForNewOutput() {
var outputUpdatePanel = document.getElementById("OutputUpdatePanel");
var pageScript = outputUpdatePanel.innerHTML;
if (script != pageScript) {
script = pageScript;
ScrollToBottom();
}
setTimeout("CheckForNewOutput()", 100);
}
function ScrollToBottom() {
$('#OutputPanel').scrollTop($('#OutputUpdatePanel').height());
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true" LoadScriptsBeforeUI="true" />
<div id="scriptModal">
<div id="ScriptInputOutput">
<asp:Panel ID="OutputPanel" runat="server" Width="700" Height="250" ScrollBars="Vertical"
Style="margin: 10px auto; border: 1px solid #CCC; padding: 5px;" ClientIDMode="Static">
<controls:ScriptOutput ID="ScriptOutputControl" runat="server" />
</asp:Panel>
<asp:Panel ID="InputPanel" runat="server" DefaultButton="btnScriptInput" >
<asp:TextBox ID="txtInput" runat="server" ClientIDMode="Static" onkeypress="ScriptInputKeypress(event)" />
<asp:HiddenField ID="hiddenInput" runat="server" ClientIDMode="Static" />
<asp:Button ID="btnScriptInput" runat="server" Text="Script Input" ClientIDMode="Static" OnClick="btnScriptInput_Click" style="display:none" />
<asp:Button ID="btnExit" runat="server" CssClass="floatRight" Text="Exit" OnClick="btnExit_Click" />
</asp:Panel>
</div>
</div>
<asp:Literal ID="litScript" runat="server" />
<ul id="breadcrumb">
<li>Main page ></li>
<li class="current">Scripts</li>
</ul>
<div class="content">
<h2>
<asp:Label ID="lblHeader" runat="server" Text="Scripts" /></h2>
<div class="clear">
</div>
<div class="table-content">
<asp:Label ID="lblMessage" runat="server" CssClass="redMessage" />
<asp:Repeater ID="rptScripts" runat="server" OnItemCommand="rptScripts_ItemCommand">
<HeaderTemplate>
<table class="table" cellpadding="0" cellspacing="0">
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Location
</th>
<th>
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("ScriptId") %>
</td>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("Path") %>
</td>
<td>
<asp:LinkButton ID="btnRunScript" runat="server" Text="Run" CommandName="Run" CommandArgument='<%# Eval("ScriptId") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div>
</div>
</div>
</div>
<script type="text/javascript" language="javascript">
CheckForNewOutput();
</script>
</asp:Content>
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MITool.Data.ScriptManager;
using System.Diagnostics;
using System.IO;
using System.Web.Security;
using System.Web.Services;
using System.Collections.Concurrent;
using System.Threading;
namespace MITool
{
public partial class Scripts : System.Web.UI.Page
{
ConcurrentQueue<char> ScriptOutputQueue
{
get
{
return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
}
set
{
Session["ScriptOutputQueue"] = value;
}
}
Process CurrentProcess
{
get
{
return (Process)Session["CurrentProcess"];
}
set
{
Session["CurrentProcess"] = value;
}
}
bool ScriptRunning
{
get
{
if (CurrentProcess == null)
return false;
if (!CurrentProcess.HasExited || !CurrentProcess.StandardOutput.EndOfStream)
return true;
return false;
}
}
bool OutputProcessing
{
get
{
if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
return true;
return false;
}
}
Thread OutputThread;
void Reset()
{
ScriptOutputControl.SetTimerEnabled(false);
ScriptOutputControl.ClearOutputText();
if (CurrentProcess != null && !CurrentProcess.HasExited)
CurrentProcess.Kill();
if (OutputThread != null && OutputThread.IsAlive)
OutputThread.Abort();
ScriptOutputQueue = new ConcurrentQueue<char>();
litScript.Text = string.Empty;
txtInput.Text = string.Empty;
}
void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
Reset();
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string role = id.Ticket.UserData;
ScriptData data = new ScriptData();
List<Script> scripts = data.GetScriptsByRole(role);
rptScripts.DataSource = scripts;
rptScripts.DataBind();
}
protected void rptScripts_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Run": StartScript(Int32.Parse(e.CommandArgument.ToString()));
break;
}
}
void StartScript(int id)
{
if (ScriptRunning || OutputProcessing)
return;
Reset();
ScriptData data = new ScriptData();
History history = new History()
{
UserName = HttpContext.Current.User.Identity.Name,
BatchFileId = id,
DateRun = DateTime.Now
};
data.CreateHistory(history);
Script script = data.GetScript(id);
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = script.Path,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
CurrentProcess = new Process();
CurrentProcess.StartInfo = psi;
OutputThread = new Thread(Output);
CurrentProcess.Start();
OutputThread.Start();
ScriptOutputControl.SetTimerEnabled(true);
litScript.Text = "<script type=\"text/javascript\" language=\"javascript\">ShowScriptModal();</script>";
SetFocus("txtInput");
}
void Output()
{
while (ScriptRunning)
{
var x = CurrentProcess.StandardOutput.Read();
if (x != -1)
ScriptOutputQueue.Enqueue((char)x);
}
}
public void btnScriptInput_Click(object sender, EventArgs e)
{
string input = hiddenInput.Value.ToString();
ScriptOutputControl.Input(input);
foreach (char x in input.ToArray())
{
if (CurrentProcess != null && !CurrentProcess.HasExited)
{
CurrentProcess.StandardInput.Write(x);
}
Thread.Sleep(1);
}
}
protected void btnExit_Click(object sender, EventArgs e)
{
Reset();
}
}
}
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ScriptOutput.ascx.cs"
Inherits="MITool.Controls.ScriptOutput" %>
<asp:Label ID="lblStats" runat="server" Style="color: Red" />
<br />
<asp:UpdatePanel ID="OutputUpdatePanel" runat="server" ClientIDMode="Static">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
<asp:AsyncPostBackTrigger ControlID="btnScriptInput" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Literal ID="litOutput" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Timer ID="UpdateTimer" Interval="100" runat="server" OnTick="UpdateTimer_Tick" Enabled="false" />
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace MITool.Controls
{
public partial class ScriptOutput : System.Web.UI.UserControl
{
string Output
{
get
{
if (Session["Output"] != null)
return Session["Output"].ToString();
return string.Empty;
}
set
{
Session["Output"] = value;
}
}
ConcurrentQueue<char> ScriptOutputQueue
{
get
{
return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
}
set
{
Session["ScriptOutputQueue"] = value;
}
}
Process CurrentProcess
{
get
{
return (Process)Session["CurrentProcess"];
}
set
{
Session["CurrentProcess"] = value;
}
}
bool ScriptRunning
{
get
{
if (CurrentProcess == null)
return false;
if (!CurrentProcess.HasExited || CurrentProcess.StandardOutput.Peek() != -1)
return true;
return false;
}
}
bool OutputProcessing
{
get
{
if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
return true;
return false;
}
}
public void SetTimerEnabled(bool enabled)
{
UpdateTimer.Enabled = enabled;
}
public void ClearOutputText()
{
Output = string.Empty;
litOutput.Text = Output;
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
ProcessOutput();
if (!ScriptRunning && !OutputProcessing)
{
UpdateTimer.Enabled = false;
Output += "<br />// SCRIPT END //<br />";
litOutput.Text = Output;
}
}
public void Input(string s)
{
Output += "<br />// " + s + "<br />";
}
void ProcessOutput()
{
string s = string.Empty;
while (ScriptOutputQueue != null && ScriptOutputQueue.Any())
{
char x;
if (ScriptOutputQueue.TryDequeue(out x))
{
s += x;
}
}
if (s != string.Empty)
{
s = Server.HtmlEncode(s);
s = s.Replace("\r\n", "<br />");
Output += s;
}
litOutput.Text = Output;
}
}
}
Related
can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.
I here to seek an advice ,what is the best approach.
here is the scenario.
I am building my project ASP.NET (C#)
I need to add an dynamic drop down box based on that two other text box related to drop down.
for example :
I have a button called "ADD LANDSCAPE", every time this triggered, i have to create an dynamic drop down "ddlLandscap" and two text boxes so the user can enter landscape value for each text box.
Can you guys please advise what's the best approach
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CS1.aspx.cs" Inherits="workout.CS1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="../jquery/jquery-ui.css" rel="stylesheet" />
<script src="../jquery/jquery-1.12.0.js"></script>
<script src="../jquery/jquery-ui.js"></script>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.table {
border: 1px solid #ccc;
border-collapse: collapse;
}
.table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
.table th, .table td {
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers1" CssClass="table" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Slno" ItemStyle-Width="50px" ItemStyle-CssClass="Slno">
<ItemTemplate>
<%# Eval("Slno") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
<ItemTemplate>
<%# Eval("Country")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Option">
<ItemTemplate>
<asp:Button ID="lnkDelete" runat="server" Text="Delete" OnClientClick="Confirmationbox(this);" />
<asp:Button ID="btn_update" runat="server" Text="Update" OnClientClick="updateable(this);" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnNewUser" runat="server" Text="Add" OnClientClick="return false;" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" OnClientClick="formatData()" />
<br />
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<div id="dialog-form-edit" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<asp:HiddenField ID="hdslno" runat="server" Value="" />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="TextBox1" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="TextBox2" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<br />
<script type="text/javascript">
var dialog,editDialog;
function formatData() {
var formatdata = "";
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) || $( this ).hasClass( "Name" ) || $( this ).hasClass( "Country" ) ) {
formatdata += $( this ).html() + "|";
}
} );
formatdata += ",";
} );
alert( formatdata );
return false;
}
$(function () {
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": AddRow,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form').data('param');
if (nr) {
$("#txtName").val(nr);
} else {
$("#txtName").val("");
}
}
});
editDialog = $("#dialog-form-edit").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": UpdateRow,
Cancel: function () {
editDialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form-edit').data('param');
console.log(nr);
$( "#hdslno" ).val( nr.slno );
$("#TextBox1").val(nr.name);
$("#TextBox2").val(nr.country);
}
});
});
$("#btnNewUser").button().on("click", function () {
dialog.dialog("open");
});
function Confirmationbox(obj) {
if (confirm("Do you want to delete this Customer?")) {
var row = $(obj).closest("tr");
row.remove();
}
return true;
}
function updateable(obj) {
var row = $(obj).closest("tr");
var slno = $(row).find("td").eq(0).html();
var name = $(row).find("td").eq(1).html();
var country = $(row).find("td").eq(2).html();
try {
var json = {
slno: slno,
name: name,
country: country
};
editDialog.data('param', json).dialog("open");
event.preventDefault();
} catch (e) {
alert(e);
}
return false;
}
function UpdateRow() {
var slno = $( "#hdslno" ).val();
var m_Name = $( "#TextBox1" ).val();
var m_Country = $( "#TextBox2" ).val();
var row = null;
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) && $( this ).html() == slno ) {
row = $( this ).closest( "tr" );
}
} )
} );
if ( row ) {
$( row ).find( "td" ).eq( 1 ).html( m_Name );
$( row ).find( "td" ).eq( 2 ).html( m_Country );
}
editDialog.dialog( "close" );
return false;
}
function AddRow() {
//Reference the GridView.
var gridView = document.getElementById("<%=gvCustomers1.ClientID %>");
//Reference the TBODY tag.
var tbody = gridView.getElementsByTagName("tbody")[0];
//Reference the first row.
var row = tbody.getElementsByTagName("tr")[1];
//Check if row is dummy, if yes then remove.
if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
tbody.removeChild(row);
}
//Clone the reference first row.
row = row.cloneNode(true);
var legnth = gridView.rows.length;
SetValue1(row, 0, "Slno", legnth);
//Add the Name value to first cell.
var txtName = document.getElementById("<%=txtName.ClientID %>");
SetValue(row, 1, "name", txtName);
//Add the Country value to second cell.
var txtCountry = document.getElementById("<%=txtCountry.ClientID %>");
SetValue(row, 2, "country", txtCountry);
//Add the row to the GridView.
tbody.appendChild(row);
dialog.dialog("close");
return false;
}
function SetValue(row, index, name, textbox) {
row.cells[index].innerHTML = textbox.value;
textbox.value = "";
}
function SetValue1(row, index, name,leng) {
row.cells[index].innerHTML = leng;
}
</script>
<asp:HiddenField ID="hdTableValues" runat="server" Value="" />
</form>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace workout
{
public partial class CS1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
string query = "SELECT '' Slno, Name, Country FROM dd_Detils";
string constr = "Data Source=localhost;Initial Catalog=DataBase;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 0)
{
//If no records then add a dummy row.
dt.Rows.Add();
}
gvCustomers1.DataSource = dt;
gvCustomers1.DataBind();
}
protected void Submit(object sender, EventArgs e)
{
int cnt = gvCustomers1.Rows.Count;
if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["country"]))
{
//Fetch the Hidden Field values from the Request.Form collection.
string[] names = Request.Form["name"].Split(',');
string[] countries = Request.Form["country"].Split(',');
//Loop through the values and insert into database table.
for (int i = 0; i < names.Length; i++)
{
string constr = "Data Source=localhost;Initial Catalog=Database;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dd_Detils VALUES(#Name, #Country)"))
{
cmd.Parameters.AddWithValue("#Name", names[i]);
cmd.Parameters.AddWithValue("#Country", countries[i]);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
//Refresh the page to load GridView with records from database table.
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
I am working on resource files. I can now read resx file and get it populate the data into the grid-view. now here is my question now,
On a run time, i want to be able to edit the columns and also be able to click empty columns and click save to save my changes. How do i do that. please help me as i have tried many examples and it didn't work.
my code below,
private void btnNewfile_Click(object sender, EventArgs e)
{
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[] { oDataSet.Tables["data"].Rows[i][0].ToString(), oDataSet.Tables["data"].Rows[i][1].ToString(), font, datestamp, commentVal };
Gridview_Output.Rows.Add(row);
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(PathSelection);
}
Save button(the user must be able to save the file created or edit to any location (C drive))
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save Resource Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "resx";
saveFileDialog1.Filter = "Save Resource Files (*.resx)|*.resx";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//nere i need the user to save to any location he want not textbox.
txtOutputfile.Text = saveFileDialog1.FileName;
}
//oDataSet.Tables.Add("Data");
oDataSet.WriteXml(PathSelection);
versionIncrement();
MessageBox.Show("Successfully added ");
}
See if the below code helps.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="UpdateResource.aspx.cs" Inherits="UpdateResource" %>
<!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>Update Resource</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
//Enable Disable all TextBoxes when Header Row CheckBox is checked.
$("[id*=chkHeader]").bind("click", function () {
var chkHeader = $(this);
//Find and reference the GridView.
var grid = $(this).closest("table");
//Loop through the CheckBoxes in each Row.
$("td", grid).find("input[type=checkbox]").each(function () {
//If Header CheckBox is checked.
//Then check all CheckBoxes and enable the TextBoxes.
if (chkHeader.is(":checked")) {
$(this).attr("checked", "checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
} else {
$(this).removeAttr("checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
}
});
});
//Enable Disable TextBoxes in a Row when the Row CheckBox is checked.
$("[id*=chkRow]").bind("click", function () {
//Find and reference the GridView.
var grid = $(this).closest("table");
//Find and reference the Header CheckBox.
var chkHeader = $("[id*=chkHeader]", grid);
//If the CheckBox is Checked then enable the TextBoxes in thr Row.
if (!$(this).is(":checked")) {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
} else {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
}
//Enable Header Row CheckBox if all the Row CheckBoxes are checked and vice versa.
if ($("[id*=chkRow]", grid).length == $("[id*=chkRow]:checked", grid).length) {
chkHeader.attr("checked", "checked");
} else {
chkHeader.removeAttr("checked");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="cmbResources" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cmbResources_SelectedIndexChanged"
Width="275px">
</asp:DropDownList>
<br />
<br />
<asp:DataGrid ID="gridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
BorderColor="Black" BorderStyle="Groove" ForeColor="#333333" Width="500px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%= ++indexNum %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="English Word">
<ItemTemplate>
<%# DataBinder.Eval(Container,"DataItem.Key") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Translated Word">
<ItemTemplate>
<%--<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
BorderStyle="Groove" disabled="disabled"></asp:TextBox>--%>
<asp:TextBox ID="txtTrans" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
Enabled="false" BorderStyle="Groove"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<%--<asp:TemplateColumn>
<ItemTemplate>
<a href='editresource.aspx?key=<%# DataBinder.Eval(Container,"DataItem.Key") %>&file=<%=cmbResources.SelectedItem.Text %>&id=<%=indexNum - 1 %>'>
Edit</a>
</ItemTemplate>
</asp:TemplateColumn>--%>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<FooterStyle Font-Bold="True" ForeColor="White" />
<SelectedItemStyle Font-Bold="True" ForeColor="Navy" />
<PagerStyle ForeColor="#333333" HorizontalAlign="Center" />
<ItemStyle ForeColor="#333333" Font-Size="Small" Font-Names="verdana" />
<HeaderStyle Font-Bold="True" />
</asp:DataGrid>
<br />
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Xml;
public partial class UpdateResource : System.Web.UI.Page
{
public int indexNum = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//string resourcespath = Request.PhysicalApplicationPath + "App_GlobalResources";
//DirectoryInfo dirInfo = new DirectoryInfo(resourcespath);
//foreach (FileInfo filInfo in dirInfo.GetFiles())
//{
// string filename = filInfo.Name;
// cmbResources.Items.Add(filename);
//}
//cmbResources.Items.Insert(0, new ListItem("Select a Resource File"));
string[] filePaths = Directory.GetFiles(#"C:\Users\D1956\Desktop\ResourceEdit", "*.aspx");
foreach (string file in filePaths)
{
string[] f = file.Split(new char[] { '\\' });
cmbResources.Items.Add(f[f.Length - 1]);
}
}
}
protected void cmbResources_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbResources.SelectedIndex != 0)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
ResXResourceReader RrX = new ResXResourceReader(stream);
IDictionaryEnumerator RrEn = RrX.GetEnumerator();
SortedList slist = new SortedList();
while (RrEn.MoveNext())
{
slist.Add(RrEn.Key, RrEn.Value);
}
RrX.Close();
stream.Dispose();
gridView1.DataSource = slist;
gridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
string filename1 = filename.Remove(filename.Length - 5);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNodeList nlist = xmlDoc.GetElementsByTagName("data");
for (int i = 0; i < gridView1.Items.Count; i++)
{
CheckBox chkItem = (CheckBox)gridView1.Items[i].FindControl("chkRow");
if (chkItem.Checked)
{
XmlNode childnode = nlist.Item(i);
XmlNode lastnode = childnode.SelectSingleNode("value");
TextBox txtTran = (TextBox)gridView1.Items[i].FindControl("txtTrans");
lastnode.InnerText = txtTran.Text.ToString();
}
}
xmlDoc.Save(filename1 + "_1" + ".resx");
}
}
You may have to edit the !IsPostback part.
I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.
I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.