?
Solved

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

Posted on 2008-10-23
30
Medium Priority
?
206 Views
Last Modified: 2008-10-24
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

0
Comment
Question by:trumpman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 14
  • 12
  • 2
  • +1
30 Comments
 
LVL 6

Expert Comment

by:divyeshhdoshi
ID: 22783744
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
 

Author Comment

by:trumpman
ID: 22783812
@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
 
LVL 2

Expert Comment

by:JasonChandler
ID: 22783909
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
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!

 

Author Comment

by:trumpman
ID: 22783964
@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
 
LVL 2

Expert Comment

by:JasonChandler
ID: 22784301
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
 
LVL 6

Expert Comment

by:divyeshhdoshi
ID: 22784307
use

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

Expert Comment

by:prairiedog
ID: 22790029
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
 

Author Comment

by:trumpman
ID: 22793006
@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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22793165
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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22793175
And you don't need your current ItemDataBound, because it is not going to help you anything.
0
 

Author Comment

by:trumpman
ID: 22793459
@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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22797254
Because you set Repeater's EnableViewState=False and you will lose all values upon postbacks. Change it to True.
0
 

Author Comment

by:trumpman
ID: 22797477
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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22797536
The foreach loop should be like this:
foreach (RepeateItemr r in Repeater2.Items)  
0
 

Author Comment

by:trumpman
ID: 22797655
@ 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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22797837
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
 

Author Comment

by:trumpman
ID: 22799241
@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
 

Author Comment

by:trumpman
ID: 22799259
@PraireDog:

FYI:

cmd4.Parameters.AddWithValue("@navID", "Wednesday");
 in the above code... replace "Wednesday" with TxtBox.Text ... results are the same though.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22799445
What data type is @navID? What is the length?
0
 

Author Comment

by:trumpman
ID: 22799485
varchar(30) ...the name NavID is misleading.  It stores a string value instead of an int ID like it sounds.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22799599
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
 

Author Comment

by:trumpman
ID: 22799642
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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22799717
So, it seems that the TextBox somehow does not contain value. Anywhere in your code-behind, do you modify the TextBox properties?
0
 

Author Comment

by:trumpman
ID: 22799795
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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22799856
Where is Button1 defined? Can you post your ASPX page?
0
 

Author Comment

by:trumpman
ID: 22799903
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
 
LVL 22

Expert Comment

by:prairiedog
ID: 22799978
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
 

Author Comment

by:trumpman
ID: 22800146
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
 
LVL 22

Accepted Solution

by:
prairiedog earned 2000 total points
ID: 22800213
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
 

Author Comment

by:trumpman
ID: 22800491
@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

Featured Post

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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses
Course of the Month14 days, 13 hours left to enroll

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question