How do I call the value of a Text Box via a dynamcially created ID?

Hello,

I am using a Repeater to list a collection of values in form text boxes.  The text box IDs are created dynamically.  I need to be able to access the same IDs to update values respectively for each box.  The code below includes the snippit I use to read assign the IDs and my attempt to use the IDs to update SQL.  However, the db does not update.  I am unsure as to the problem since the code does not post any errors.

Any help is greatly appreciated.


// Get values for text box
protected void repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        
        
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            
                TextBox txtBox = (TextBox)e.Item.FindControl("txtBox");
                txtBox.ID += e.Item.ItemIndex.ToString();
               
            
        }
        
    }
 
 
// update the values with
foreach (Repeater r in Repeater2.Items) {
         
        SqlCommand cmd4 = new SqlCommand("sp_updateMainNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        cmd4.CommandType = CommandType.StoredProcedure;
 
        
        cmd4.Parameters.AddWithValue("@navID", (TextBox)r.FindControl("txtBox"));
        cmd4.Parameters.AddWithValue("@navURL", "1");
        cmd4.Parameters.AddWithValue("@navOrder", "1");
            cmd4.Parameters.AddWithValue("@id", "1");
            cmd4.Connection.Open();
            cmd4.ExecuteNonQuery();
            cmd4.Connection.Close();
        }

Open in new window

trumpmanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

divyeshhdoshiCommented:
Hope will help u
cmd4.Parameters.AddWithValue("@navID", ((TextBox)r.FindControl("txtBox")).Text);
cmd4.Parameters.AddWithValue("@navURL", "1");
cmd4.Parameters.AddWithValue("@navOrder", "1");
cmd4.Parameters.AddWithValue("@id", "1");
0
trumpmanAuthor Commented:
@divyeshhdoshi:

Thank you for your reply.  I tried your suggestion without success.  As before, no errors were posted either which is making this difficult to debug.  
0
JasonChandlerCommented:
Try
Dim TxtBox As TextBox = Ctype(e.Item.FindControl("txtBox"),Textbox)

cmd4.Parameters.AddWithValue("@navID",TxtBox.Text)

This Is a VB.NET Example, but should work for you.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

trumpmanAuthor Commented:
@JasonChandler:

I tried the following C# version of your code:

TextBox TxtBox = (TextBox)r.Items.FindControl("txtBox");
cmd4.Parameters.AddWithValue("@navID", TxtBox.Text);

However, I receive the following compiler error:

 'System.Web.UI.WebControls.RepeaterItemCollection' does not contain a definition for 'FindControl'
0
JasonChandlerCommented:
Hi Try Looking at this post on MSDN. I think it may help you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.items.aspx
Let me Know, Ill try to look at this later for you.
0
divyeshhdoshiCommented:
use

TextBox TxtBox = (TextBox)r.FindControl("txtBox");
cmd4.Parameters.AddWithValue("@navID", TxtBox.Text);
0
prairiedogCommented:
Don't understand why you do this: cmd4.Parameters.AddWithValue("@navID", (TextBox)r.FindControl("txtBox"));
You are assigning a TextBox control itselft to "@navID"? It seems that "@navID" is expecting an integer, or the TextBox.ID, right? Try this as the attached code snippet.
And don't understand your ItemDataBound event handler, either. Are you trying to save ItemIndex for the later update?

cmd4.Parameters.AddWithValue("@navID", r.ItemIndex);

Open in new window

0
trumpmanAuthor Commented:
@prairedog:

Okay.  Perhaps I should just explain what I am needing to do.  My code may be misleading.  I need a series of textboxes that are created through a Repeater and intialized to a Value that is stored in SQL.  If the value of these text boxes is changed by the user, I need to be able to update the Respective slot in SQL at Submit with this change.  Could you please advise the best implementation of such task?  

Thank you.
0
prairiedogCommented:
If you define your TextBoxes in Repeater's ItemTemplate, and it seems that it is your case, then divyeshhdoshi's solution (ID# http://22784307) should work.
0
prairiedogCommented:
And you don't need your current ItemDataBound, because it is not going to help you anything.
0
trumpmanAuthor Commented:
@prairedog:

What you are saying makes total sense.   However, I have tried this but it does not update my dbase.  Just to ensure I am not overlooking the obvious, I have attached the code-behind and .aspx in their current state using @divyeshhdoshi's solution.

I appreciate your guidance.

..again this code posts no errors.
using System;
using System.Data;
using System.Configuration;
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.Data.SqlClient;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        
 
 
        foreach (Repeater r in Repeater2.Items) 
        {
        SqlCommand cmd4 = new SqlCommand("sp_updateMainNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
            cmd4.CommandType = CommandType.StoredProcedure;
            TextBox TxtBox = (TextBox)r.FindControl("txtBox");
            cmd4.Parameters.AddWithValue("@navID", TxtBox.Text);
            cmd4.Parameters.AddWithValue("@navURL", "1");
            cmd4.Parameters.AddWithValue("@navOrder", "1");
            cmd4.Parameters.AddWithValue("@id", "1");
            cmd4.Connection.Open();
            cmd4.ExecuteNonQuery();
            cmd4.Connection.Close();
 
        }
 
 
        
    }
 
    
 
 
    
}
 
 
.aspx
 
<%@ Page Language="C#" MasterPageFile="update.master"  CodeFile="update.aspx.cs" Inherits="_Default" Title="" %>
 
 
 
 
<asp:Content ID="mainnav" ContentPlaceHolderID="mainnav" Runat="server">
<asp:repeater ID="Repeater2" DataSourceID="MainNavSQL" EnableViewState="false" runat="server">
                                <ItemTemplate>
                               
                                <asp:TextBox ID='txtBox' value='<%#Eval ("NavId") %>' runat="server"></asp:TextBox>
                                
                                 
                                </ItemTemplate>
                             </asp:repeater></asp:Content>

Open in new window

0
prairiedogCommented:
Because you set Repeater's EnableViewState=False and you will lose all values upon postbacks. Change it to True.
0
trumpmanAuthor Commented:
Thanks.  That makes sense, but now I am getting:

Unable to cast object of type 'System.Web.UI.WebControls.RepeaterItem' to type 'System.Web.UI.WebControls.Repeater'.
0
prairiedogCommented:
The foreach loop should be like this:
foreach (RepeateItemr r in Repeater2.Items)  
0
trumpmanAuthor Commented:
@ PraireDog:

RepeaterItem * takes care of the error.  On postback, the box displays the update value.  However, SQL is not being updated.  If I remove TxtBox.Text and replace it with a string like "test", SQL updates just fine.  TxtBox.Text is an empty value.  Any ideas?

I really appreciate your help!
0
prairiedogCommented:
Can you put a "try/catch/finally" block around the code that handles the DB update to see if you can catch any exception errors?
0
trumpmanAuthor Commented:
@PraireDog:

This code executes without posting any errors or updating dbase.  
oreach (RepeaterItem r in Repeater2.Items) {
 
 
 
            try
            {
                SqlCommand cmd4 = new SqlCommand("sp_updateMainNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
                cmd4.CommandType = CommandType.StoredProcedure;
                TextBox TxtBox = (TextBox)r.FindControl("txtBox");
                cmd4.Parameters.AddWithValue("@navID", "Wednesday");
                cmd4.Parameters.AddWithValue("@navURL", "1");
                cmd4.Parameters.AddWithValue("@navOrder", "1");
                cmd4.Parameters.AddWithValue("@id", "1");
                cmd4.Connection.Open();
                cmd4.ExecuteNonQuery();
                cmd4.Connection.Close();
 
            }
 
            catch (System.InvalidOperationException ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                str += "\n" + "\n";
                str += "\n" + "Stack Trace :" + ex.StackTrace;
                Console.WriteLine(str, "Specific Exception");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                Console.WriteLine(str, "Database Exception");
            }
            catch (System.Exception ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                Console.WriteLine(str, "Generic Exception");
            }
 
            finally { }
 
 
            
            
 
        }

Open in new window

0
trumpmanAuthor Commented:
@PraireDog:

FYI:

cmd4.Parameters.AddWithValue("@navID", "Wednesday");
 in the above code... replace "Wednesday" with TxtBox.Text ... results are the same though.
0
prairiedogCommented:
What data type is @navID? What is the length?
0
trumpmanAuthor Commented:
varchar(30) ...the name NavID is misleading.  It stores a string value instead of an int ID like it sounds.
0
prairiedogCommented:
I am puzzled. So you are saying that:
cmd4.Parameters.AddWithValue("@navID", "Wednesday");  // not working
cmd4.Parameters.AddWithValue("@navID", "test");   // working
cmd4.Parameters.AddWithValue("@navID", TxtBox.Text); // not workding


 
0
trumpmanAuthor Commented:
No.  The post with Wednesday was an oops. Sorry.


cmd4.Parameters.AddWithValue("@navID", "Wednesday");  // working

cmd4.Parameters.AddWithValue("@navID", "test");   // working

cmd4.Parameters.AddWithValue("@navID", TxtBox.Text); // not working
0
prairiedogCommented:
So, it seems that the TextBox somehow does not contain value. Anywhere in your code-behind, do you modify the TextBox properties?
0
trumpmanAuthor Commented:
This is the code in its entirety.
using System;
using System.Data;
using System.Configuration;
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.Data.SqlClient;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        SqlCommand cmd = new SqlCommand("sp_insertMainNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        cmd.CommandType = CommandType.StoredProcedure;
        
        cmd.Parameters.AddWithValue("@navID", mainNavID.Text);
        cmd.Parameters.AddWithValue("@navURL", mainNavURL.Text);
        cmd.Parameters.AddWithValue("@active", "1");
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
           
 
 
        
 
        SqlCommand cmd2 = new SqlCommand("sp_insertStoreNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        cmd2.CommandType = CommandType.StoredProcedure;
 
        cmd2.Parameters.AddWithValue("@navID", storeNavID.Text);
        cmd2.Parameters.AddWithValue("@navURL", storeNavURL.Text);
 
        cmd2.Connection.Open();
        cmd2.ExecuteNonQuery();
        cmd2.Connection.Close();
 
        SqlCommand cmd3 = new SqlCommand("sp_insertInfoNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        cmd3.CommandType = CommandType.StoredProcedure;
 
        cmd3.Parameters.AddWithValue("@navID", infoNavID.Text);
        cmd3.Parameters.AddWithValue("@navURL", infoNavURL.Text);
 
        cmd3.Connection.Open();
        cmd3.ExecuteNonQuery();
        cmd3.Connection.Close();
 
 
 
 
 
        foreach (RepeaterItem r in Repeater2.Items) {
 
 
 
            try
            {
                SqlCommand cmd4 = new SqlCommand("sp_updateMainNav", new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
                cmd4.CommandType = CommandType.StoredProcedure;
                TextBox TxtBox = (TextBox)r.FindControl("txtBox");
                cmd4.Parameters.AddWithValue("@navID", TxtBox.Text);
                cmd4.Parameters.AddWithValue("@navURL", "1");
                cmd4.Parameters.AddWithValue("@navOrder", "1");
                cmd4.Parameters.AddWithValue("@id", "1");
                cmd4.Connection.Open();
                cmd4.ExecuteNonQuery();
                cmd4.Connection.Close();
 
            }
 
            catch (System.InvalidOperationException ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                str += "\n" + "\n";
                str += "\n" + "Stack Trace :" + ex.StackTrace;
                Console.WriteLine(str, "Specific Exception");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                Console.WriteLine(str, "Database Exception");
            }
            catch (System.Exception ex)
            {
                string str;
                str = "Source:" + ex.Source;
                str += "\n" + "Message:" + ex.Message;
                Console.WriteLine(str, "Generic Exception");
            }
 
            finally { }
 
 
            
            
 
        }
 
 
        
    }
 
    
 
 
    
}

Open in new window

0
prairiedogCommented:
Where is Button1 defined? Can you post your ASPX page?
0
trumpmanAuthor Commented:
I am using a .master.
<%@ Master Language="C#" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
    Main Nav<br />
 
    <asp:contentplaceholder id="mainnav" runat="server">
    </asp:contentplaceholder> 
    
     <asp:contentplaceholder id="editnav" runat="server">
    </asp:contentplaceholder> 
   </form> 
    
    
</body>
</html>
 
 
... here is the .aspx:
 
<%@ Page Language="C#" MasterPageFile="update.master"  CodeFile="update.aspx.cs" Inherits="_Default" Title="" %>
 
 
 
 
<asp:Content ID="mainnav" ContentPlaceHolderID="mainnav" Runat="server">
<asp:repeater ID="Repeater2" DataSourceID="MainNavSQL" EnableViewState="true" runat="server">
                                <ItemTemplate>
                               
                                <asp:TextBox ID='txtBox' value='<%#Eval ("navID") %>' runat="server"></asp:TextBox>
                                
                                 
                                </ItemTemplate>
                             </asp:repeater></asp:Content>
 
 
<asp:Content ID="editnav" ContentPlaceHolderID="editnav" Runat="server">
<table>
<tr> 
<td style="width: 100px"> 
Name of Link:</td>
<td style="width: 100px"> 
<asp:TextBox ID="mainNavID" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td style="width: 100px"> 
URL:</td>
<td style="width: 100px"> 
<asp:TextBox ID="mainNavURL" value="33" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td style="width: 100px"> 
Name of Link:</td>
<td style="width: 100px"> 
<asp:TextBox ID="storeNavID" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td style="width: 100px"> 
URL:</td>
<td style="width: 100px"> 
<asp:TextBox ID="storeNavURL" value="33" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td style="width: 100px"> 
Name of Link:</td>
<td style="width: 100px"> 
<asp:TextBox ID="infoNavID" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td style="width: 100px"> 
URL:</td>
<td style="width: 100px"> 
<asp:TextBox ID="infoNavURL" value="33" runat="server"></asp:TextBox></td>
</tr>
<tr> 
<td colspan="2"> 
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add to DB" /></td>
</tr>
</table><br />
 
</asp:Content>

Open in new window

0
prairiedogCommented:
Your code looks ok to me.
Can you set a break point on this line?
cmd4.Parameters.AddWithValue("@navID", TxtBox.Text);
See if TxtBox.Text holds the correct data?

0
trumpmanAuthor Commented:
I can set a breakpoint but Debugging is greyed out for me in Visual Web Developer... do you have an alternate solution? Otherwise, I will start a thread to see why I can't debug.
0
prairiedogCommented:
After TextBox TxtBox = (TextBox)r.FindControl("txtBox"); add this:
Response.Write("Value of TextBox " + r.ItemIndex.ToString() + ": " + TxtBox.Text + "<br />");
It should print out a long list of the text box's value.

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trumpmanAuthor Commented:
@praireDog:

Unbelievable.  The values were as they should be so I just restarted IIS.  It is working just fine now.  Thank you for your quick and informative responses!  Your time spent has definitely earned all the points on this one.

-trumpman
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.