• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 861
  • Last Modified:

Use MasterPage TextBox

I have a GridView that uses a sproc. The sproc needs to pull an input value from a master page; instead of on the current page.  I wanted to please ask how do I specify for the sproc to use the text box from the master page.   I am using asp.net with c#.  I prefer the simplest method possible. Thanks!

Thanks.
0
jjrr007
Asked:
jjrr007
  • 8
  • 7
1 Solution
 
Juan_BarreraCommented:
Hi there,

There are a few ways to do it, this is the one I'd suggest:

1) Reference the masterPage in your Page code-behind:

<%@ MasterType VirtualPath="~/YourMasterPagePath" %>

2) Add a property to the Master page to set the text

  public string MyText
    {
        get
        {
            return MyTextBox.Text;
        }
        set {

            MyTextBox.Text = value;
        }
    }

3) Then, in your page, you can reference the property to get or set the value:

string text = Master.MyText;


0
 
jjrr007Author Commented:
I don't think that I am doing this right. I referenced the path to the master page in asp.net code.

In your example you have:
public string MyText
   {
       get
       {
           return MyTextBox.Text;
       }
       set {

           MyTextBox.Text = value;
       }
   }
 
I should replace "MyTextBox" with the actual ID of the textbox?  

Also, when I set the data set to use the value from the text box, this is how i did it:

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbWebForumConnectionString %>"
        SelectCommand="sprocname" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="Master.MyText" DefaultValue="%%%SpecialString%%%" Name="Search" PropertyName="Text"
                Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

I don't think I set the controlID correctly.  What do you suggest?  Thanks again
0
 
Juan_BarreraCommented:
You should add the property to the Mater page. "MyTextBox" is the identity of your text box. You need to change it to whatever your tb actually is:

Then, to add the parameter to the SqlDataSource, do it on code-behind, in PageLoad, like this:

SqlDataSource1.SelectParameters.Add("Search", Master.MyText);

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jjrr007Author Commented:
Thanks Juan_Barrera.  I will take those steps.  I will try this when I get in the office in the morning and let you know.

Howeve, do I still use the exact code:
SqlDataSource1.SelectParameters.Add("Search", Master.MyText);

I don't have to rename anything in the line above?  Since I am adding the code above, I will need to remove the line below from the asp.net code-right? Thanks again!

    <asp:ControlParameter ControlID="Master.MyText" DefaultValue="%%%SpecialString%%%" Name="Search" PropertyName="Text"
                Type="String" />

0
 
Juan_BarreraCommented:
Yes, you need to remove these lines:

 <SelectParameters>
            <asp:ControlParameter ControlID="Master.MyText" DefaultValue="%%%SpecialString%%%" Name="Search" PropertyName="Text"
                Type="String" />
        </SelectParameters>

Good luck!
0
 
jjrr007Author Commented:
Juan_Barrera,

I am getting an error when I tried that; the GridView's SPROC didn't obtain the default value that it needs.   I think I will need to set the Default Value in the code.  How do I add the default value to step three you provided?

Something else I am not sure about.  I have set my data properties in the ASP.NET code.  I believe the code you provided (in step three) is assuming the data properties are set in the C# code- not sure though. I have attached the data configuration that I used  in the code snippet (without the select parameters we discussed).  Should I configure the data set in C# code instead and then use the code you provided?

Thanks again for your time.  
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbWebForumConnectionString %>"
        SelectCommand="NameofStoredProcedure" SelectCommandType="StoredProcedure">
    </asp:SqlDataSource>

Open in new window

0
 
jjrr007Author Commented:
We are getting closer.  The only issue is step 3.   I am getting an error saying

[InvalidOperationException: Could not find control 'Master.MyText' in ControlParameter 'Search'.]

I just don't know how to set the control parameter to get the 'Master.MyText'.  What I did was place it in the SQLDataSource in Asp.net.  The code is the snippet.  What do you suggest that I change?

Thanks again!
                 <SelectParameters>
                    <asp:ControlParameter ControlID="Master.MyText" DefaultValue="zzzzzzz" Name="Search" PropertyName="Text"
                        Type="String" />
                </SelectParameters>

Open in new window

0
 
Juan_BarreraCommented:
Hi again!

Your SqlDataSource markup should be like you've posted before (not the last one): we'll add the parameter in code-behind, so don't include <SelectParameter> in the markup.
So, your markup should be like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbWebForumConnectionString %>"
        SelectCommand="NameofStoredProcedure" SelectCommandType="StoredProcedure">
    </asp:SqlDataSource>
 
Your code-behind to set the select parameter should be like this:
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("Search", Master.MyText);
And, to add a default value:
SqlDataSource1.SelectParameters["Search"].DefaultValue = "%%%SpecialString%%%"
Try this and let me know how it goes.
0
 
jjrr007Author Commented:
Thanks for your time.  Unfortunately, it didn't work, but I didn't get any compliation errors when I tried the most recent post.

I have left work for the day.  So what I did was I made a simple example at home.   For simplicity and time, I have attached the projects code (a simple example- 1 master, 1 form page) in the snippet.  

The GridView should use the value from TextBox2 that is in the master page, but it's not taking the value from TextBox2 on the Master Page. I have tested and it works otherwise.  What do you suggest?
*****Master Page's C# Code Below
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;
 
public partial class MasterPage : System.Web.UI.MasterPage
{
    public string MyText
    {
        get
        {
            return TextBox2.Text;
        }
        set
        {
 
            TextBox2.Text = value;
        }
    }
 
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
}
 
*****Master Page's ASP.NET Code Below
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
 
<!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>Untitled Page</title>
</head>
<body bgcolor ="lime">
    <form id="form1" runat="server">
    
    <div>
           <asp:contentplaceholder id="ContentPlaceHolder2" runat="server">
               <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><asp:Button ID="Button2"
                   runat="server" Text="Button" />
        </asp:contentplaceholder>
    <br />
    <br />
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
 
*****Default.aspx Page's C# Code Below
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;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters.Clear();
        SqlDataSource1.SelectParameters.Add("ProductID", Master.MyText);
        SqlDataSource1.SelectParameters["ProductID"].DefaultValue = "999";
    }
}
 
*****Default.aspx Page's ASP.NET Code Below
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductID" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Color" HeaderText="Color" SortExpression="Color" />
            <asp:BoundField DataField="StartDate" HeaderText="StartDate" SortExpression="StartDate" />
        </Columns>
    </asp:GridView>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksDWConnectionString %>"
       SelectCommand="NewRick" SelectCommandType="StoredProcedure">
   </asp:SqlDataSource>
 
</asp:Content>

Open in new window

0
 
Juan_BarreraCommented:
Looking at your code, let's try a small modification:

Change PageLoad to this (we don't pass the param value yet):

 protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters.Clear();
        SqlDataSource1.SelectParameters.Add("ProductID");
        SqlDataSource1.SelectParameters["ProductID"].DefaultValue = "999";
    }

And, later on the life cycle, on SqlDataSource Selecting, we set the value:

    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
       
        string text = Master.MyText;
        e.Command.Parameters["ProductID"].Value = text;
   
    }

Now, here pay attention at the value of "text". It should be what you are expecting.
0
 
jjrr007Author Commented:
I really appreciate your time.  I have modified the code listed in my last post to what you suggested.  I received a couple message  saying:

Error      1      The best overloaded method match
Error      2      Argument '1': cannot convert from 'string'       

Both of the messages above pointed to line 17, which is:
SqlDataSource1.SelectParameters.Add("ProductID");

The line above may require more than one value, so I tried to modify it to:
SqlDataSource1.SelectParameters.Add("ProductID", "");

The default values were sent, but the values from the text box were not sent that way.   The C# code with your suggestion is in the snippet below.  Everything else is the same as my last post.  What do you suggest?

Thanks again for your time!




*****Default.aspx Page's C# Code Below
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;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters.Clear();
        SqlDataSource1.SelectParameters.Add("ProductID");
***The messages refers to line above, does it another value or an ***alternative line/method?
        SqlDataSource1.SelectParameters["ProductID"].DefaultValue = "999";
    }
 
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
 
        string text = Master.MyText;
        e.Command.Parameters["ProductID"].Value = text;
 
    }
}

Open in new window

0
 
Juan_BarreraCommented:
Try this on PageLoad (just a small modification over the previous code). See how you can set any property you want on "param":

protected void Page_Load(object sender, EventArgs e)
    {
 Parameter param = new Parameter();
  param.Name = "ProductID";
 param.DefaultValue = "999";
  sql.SelectParameters.Add(param);
}

Then, we still need to check two things on SqlDataSource_Selecting:

1) Is Master null?
2) If not, is "text" empty?

  protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

        if (Master != null)
        {
            string text = Master.MyText;
            e.Command.Parameters["ProductID"].Value = text;
        }

    }

Let me know what you find about those two questions.
0
 
jjrr007Author Commented:
First off, I wanted to say thanks for your time and expertise.  I appreciate your work on this.

I tired the suggestion.  When I made the change to page's code, I received the errror:
Error      1      The name 'sql' does not exist in the current context      
The line that it referred to is: "sql.SelectParameters.Add(param);"

 I tried to answer the two questions you asked by leaving the "SqlDataSource1_Selecting" Method as you last posted and changing Page Load Procedure to:
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("ProductID", "");
SqlDataSource1.SelectParameters["ProductID"].DefaultValue = "999";

Then I added a break point right after, " if (Master != null)".  The code never reached that point.  So it seems to me that it is not finding the text box on the Master Page.

Some good news, I visited the link at http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx.  I tried the code llisted in the snippet.  When I tried the code in the snipeet, it wrote the words "Textbox Found!" in the master page's text box.  I just don't know how we can send the value from the textbox  found to the parameter. What do you suggest?

Thanks again!
    protected void Page_Load(object sender, EventArgs e)
    {
  
        SqlDataSource1.SelectParameters.Add("ProductID", "");
        ContentPlaceHolder mpContentPlaceHolder;
        TextBox mpTextBox;
        mpContentPlaceHolder =
          (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder2");
        if (mpContentPlaceHolder != null)
        {
            mpTextBox =
                (TextBox)mpContentPlaceHolder.FindControl("TextBox2");
            if (mpTextBox != null)
            {
                mpTextBox.Text = "TextBox found!";
            }
        }

Open in new window

0
 
Juan_BarreraCommented:
jjrr07, I'm glad you are getting closer.
I'm really surprised of what you say about the code not being hit. Maybe the event is not propertly hooked up, but it should be hit.
About the other approach, remember what I've said in my first post: There are a few way to achieve what you need. Still, I prefer the use of a property rather than FindControls, because, for example, a change in the structure in the MasterPage could make your code fail, without notice.

Anyway, following on my approach, this should hook the event properly:

1) In code-behind:

protected void Page_Load(object sender, EventArgs e)
    {
 Parameter param = new Parameter();
  param.Name = "ProductID";
 param.DefaultValue = "999";
 SqlDataSource1.SelectParameters.Add(param);
}


protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

        if (Master != null)
        {
            string text = Master.MyText;
            e.Command.Parameters["ProductID"].Value = text;
        }

    }


2) In markup:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnSelecting="SqlDataSource1_Selecting" ConnectionString="<%$ ConnectionStrings:AdventureWorksDWConnectionString %>"
       SelectCommand="NewRick" SelectCommandType="StoredProcedure">
   </asp:SqlDataSource>


OR., if you want to keep up with the other approach:



protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters.Clear();
       
        ContentPlaceHolder mpContentPlaceHolder;
        TextBox mpTextBox;
        mpContentPlaceHolder =
          (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder2");
        if (mpContentPlaceHolder != null)
        {
            mpTextBox =
                (TextBox)mpContentPlaceHolder.FindControl("TextBox2");
            if (mpTextBox != null)
            {
                SqlDataSource1.SelectParameters.Add("ProductId",mpTextBox.Text)
            }
        }
0
 
jjrr007Author Commented:
Thanks for your post.

I tried the suggestion without the (find control option) and I encountered the following error:

"An SqlParameter with ParameterName 'Search' is not contained by this SqlParameterCollection."

The error occured at the line, "e.Command.Parameters["Search" ].Value = text;". The parameter values are correct, I am testing it on the actual project at my work.   I have changed the default values to the actual parameter values.   I tried the other way and for some reason it didn't work.  No syntax errors were cound.  

What I did was I placed the code on the master page itself and it worked perfectly!  you have helped lead me to that solution.  Thanks again.

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 8
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now