Try something like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ObjectDataSource ods = CPUSControl1.FindControl("ObjectDataSourcecpus") as ObjectDataSource;
if (ods != null)
{
string value = DropDownListUsuarios.SelectedValue.Trim();
ods.SelectParameters["usuario"].DefaultValue = value;
ods.InsertParameters["usuario"].DefaultValue = value;
}
}
Changes to your code:
Don't catch an
Exception
if you're not going to do anything with it. (If you must re-throw an exception, usethrow;
instead ofthrow error;
to preserve the stack-trace.)Use the
as
operator for conditional casting of reference types - it's more efficient than calling.GetType()
and comparing the result to a specific type.The
SelectedValue
property is already astring
- there's no need to call.ToString()
on it.Calling
.Trim()
creates a new string; it's best to cache the result in a local variable and reuse it.You have already added the parameter to the
SelectParameters
andInsertParameters
collection via markup. You just need to retrieve the existingParameter
object and set itsDefaultValue
property.
Edit:
The InsertParameters
collection doesn't store changes in ViewState
, so you'll lose the value on post-back. The simplest solution is probably to use the Inserting
event to set the parameter value:
Main page (code-behind):
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
CPUSControl1.Usuario = DropDownListUsuarios.SelectedValue.Trim();
}
User control:
<asp:ObjectDataSource ID="ObjectDataSourcecpus" runat="server"
SelectMethod="getCPUs" TypeName="CPU" InsertMethod="saveCPUs"
OnSelecting="DataSourceCallingMethod"
OnInserting="DataSourceCallingMethod"
OnUpdating="DataSourceCallingMethod"
OnDeleting="DataSourceCallingMethod"
>
...
*User control (code-behind):
public string Usuario
{
get { return (string)ViewState["Usuario"]; }
set { ViewState["Usuario"] = value; }
}
protected void DataSourceCallingMethod(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["usuario"] = Usuario;
}