Foros del Web » Programación para mayores de 30 ;) » .NET »

Rellenar un TextBox al cambiar DropDownList median un DataSet

Estas en el tema de Rellenar un TextBox al cambiar DropDownList median un DataSet en el foro de .NET en Foros del Web. Hola foreros! tengo un problema que, ya más que un problema empieza a ser un terrible dolor de cabeza. La cuestión es que tengo q ...
  #1 (permalink)  
Antiguo 29/07/2011, 01:10
 
Fecha de Ingreso: julio-2011
Mensajes: 3
Antigüedad: 12 años, 9 meses
Puntos: 0
Rellenar un TextBox al cambiar DropDownList median un DataSet

Hola foreros! tengo un problema que, ya más que un problema empieza a ser un terrible dolor de cabeza.
La cuestión es que tengo q rellenar un textbox en función de lo que se seleccione en un DropDownList.
Mi primera idea era ejecutar una función javascript en evento SelectedItem en la cual dentro llamaría a un Ajax Method del lado del servidor. y en el proceso de vuelta rellena el textbox.
Esta idea se me ocurrió viendo este tutorial: [URL="http://www.scourdesign.com/articulos/tutoriales/net/6.php#a6"]http://www.scourdesign.com/articulos/tutoriales/net/6.php#a6[/URL]

Aunque no consigo que funcione nada de nada. Os agradecería que me echarais un cable porque la verdad que ando bastante perdido.

(En cuanto a por qué he utilizado javascript y no lo hago utilizando los eventos asp y autopostback, estoy utilizando una función javascript para validar otro datos en función de la selección del DropDownList y no se si podría hacer dos llamadas en el mismo evento.)

Alguna idea??
  #2 (permalink)  
Antiguo 01/08/2011, 13:22
Avatar de othix  
Fecha de Ingreso: mayo-2011
Ubicación: Guatemala
Mensajes: 92
Antigüedad: 12 años, 10 meses
Puntos: 9
Respuesta: Rellenar un TextBox al cambiar DropDownList median un DataSet

en los eventos del dropDownList, selectedItemChanged en este evento podes programar que te cambie de valor el texbox.text
  #3 (permalink)  
Antiguo 02/08/2011, 03:06
 
Fecha de Ingreso: julio-2011
Mensajes: 3
Antigüedad: 12 años, 9 meses
Puntos: 0
Sonrisa Respuesta: Rellenar un TextBox al cambiar DropDownList median un DataSet

Gracias por la respuesta othix, pero lo que buscaba es algo más elaborado. al final he dado con la solución indagando en el manual AJAX with ASP.NET. El ejemplo que me ha servido de ejemplo para solucionar lo que os cuento es el siguiente:

Código del lado del servidor:

Código:
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.Text;
public partial class AsyncDropDownListExample_AsyncDropDownListExample :
System.Web.UI.Page, ICallbackEventHandler
{
private DataSet lookupData = null;
protected void Page_Load(object sender, EventArgs e)
{
// Get our callback event reference
string js = Page.ClientScript.GetCallbackEventReference(this,“arg”,“OnServerCallComplete”, “ctx”, “OnServerCallError”, true);
// Create a simplified wrapper method
StringBuilder newFunction = new StringBuilder();
newFunction.Append(“function StartAsyncCall(arg, ctx) “);
newFunction.Append(“{ “);
newFunction.Append(js);
newFunction.Append(“ } “);
// Now register it
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“NewAsyncMethod”,
newFunction.ToString(), true);
}
#region ICallbackEventHandler Members
public string GetCallbackResult()
{
StringBuilder ids = new StringBuilder();
StringBuilder names = new StringBuilder();
int rowCnt = 0;
int numRows = lookupData.Tables[0].Rows.Count;
foreach (DataRow row in lookupData.Tables[0].Rows)
{
rowCnt++;
ids.Append(row[“ID”].ToString());
if (rowCnt < numRows) // Only append a separator if its NOT the last
element
ids.Append(“|”); // Include a data element separator character
names.Append(row[“Name”].ToString());
if (rowCnt < numRows) // Only append a separator if its NOT the last element
names.Append(“|”); // Include a data element separator character
}
// Make one big string, separating the sets of data with a tilde ‘~’
string returnData = string.Format(“{0}~{1}”, ids.ToString(),
names.ToString());
return returnData;
}
public void RaiseCallbackEvent(string eventArgument)
{
System.Threading.Thread.Sleep(2000); // Simulate a delay
lookupData = GetLookupValuesFromDatabase();
}
#endregion
#region GetLookupValuesFromDatabase helper method
private DataSet GetLookupValuesFromDatabase()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn idCol = new DataColumn(“ID”, typeof(int));
DataColumn nameCol = new DataColumn(“Name”, typeof(string));
dt.Columns.Add(idCol);
dt.Columns.Add(nameCol);
dt.AcceptChanges();
DataRow newRow = null;
newRow = dt.NewRow();
newRow[idCol] = 1;
newRow[nameCol] = “Joe Bloggs ID#1”;
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow[idCol] = 2;
newRow[nameCol] = “Mr A. Nonymous ID#2”;
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow[idCol] = 3;
newRow[nameCol] = “Mrs N. Extdoorneighbour ID#3”;
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow[idCol] = 4;
newRow[nameCol] = “Mr. Pea Body ID#4”;
dt.Rows.Add(newRow);
ds.Tables.Add(dt);
ds.AcceptChanges();
return ds;
}
#endregion
}
Web Page:
Código:
<%@ Page Language=”C#” AutoEventWireup=”true”
CodeFile=”AsyncDropDownListExample.aspx.cs”
Inherits=”AsyncDropDownListExample_AsyncDropDownListExample” %>
<!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>Asynchronous Drop Down List Example</title>
<script type=”text/javascript”>
function LoadListItems()
{
StartAsyncCall(null,null);
}
function OnServerCallComplete(arg, ctx)
{
var idsAndNames = arg.split(“~”);
var ids = idsAndNames[0].split(“|”);
var names = idsAndNames[1].split(“|”);
var htmlCode;
var ddl = document.getElementById(“ddlList”);
for (var i=0; i < ids.length; i++)
{
htmlCode = document.createElement(‘option’);
// Add the new <OPTION> node to our <SELECT> drop list
ddl.options.add(htmlCode);
// Set the <OPTION> display text and value;
htmlCode.text = names[i];
htmlCode.value = ids[i];
}
// Enable our drop down list as it
// should have some values now.
ddl.disabled = false;
}
function OnServerCallError(err, ctx)
{
alert(“There was an error processing the request! Error was [“ + err +
“]”);
}
function OnDropListSelectChanged()
{
var ddl = document.getElementById(“ddlList”);
// Display selected value
var msg = document.getElementById(“msg”);
msg.firstChild.nodeValue=ddl.value;
}
</script>
</head>
<body onload=”LoadListItems();”>
<form id=”form1” runat=”server”>
<div>
<select id=”ddlList” disabled=”false”
onchange=”OnDropListSelectChanged();”>
<option>(Loading values from the Server)</option>
</select>
</div>
<hr />
<div>
<label>Value Selected:&nbsp;</label><span id=”msg”>{none}</span>
</div>
</form>
</body>
</html>
Espero que le pueda ser útil a alguien más...Saludos!! ;)

Etiquetas: net
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:44.