Reputation: 81
I'm pretty new in the programming world and having a problem with ID's in my application. I have a database with ships and for every ship in the database, my code will create a div with a textbox (where i want to put the name of the ship that comes from the database). But every textbox has to have a unique ID to write data to it from the database.
Here is my code:
for (int i = 0; i < count; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv.ID = "createDiv";
this.Controls.Add(createDiv);
TextBox tb_name = new TextBox();
tb_name.ID = **"CreateT1";**
createDiv.Controls.Add(new LiteralControl
("<div class='form-group'><div class='clearfix' ></div><div class='row'><div class='col-md-3'></div><div class='col-md-3'> Schipnaam: <input type='text' **id='CreateT1'** runat='server'/></div></div></div>"));
The ID of the textbox isnow CreateT1, but i want it to be unique and generated. I have heard that my options are: Guid.NewGuid().ToString(n) or auto increment but i have no idea how to use them.
Hope you guys have the answer or other options!
Upvotes: 0
Views: 586
Reputation: 18465
Guid.NewGuid().ToString(n) or auto increment
Guid.NewGuid()
createDiv.ID = Guid.NewGuid().ToString();
tb_name.ID= Guid.NewGuid().ToString();
Auto increment via index
createDiv.ID = "createDiv-" + i;
tb_name.ID = "createTextBox-" + i;
Hope it helps.
Upvotes: 1
Reputation: 2329
If you want a quick and temporary fix, try using the increment value i
itself, since it iterates over all your database rows, so it will definitely be unique.
If you have other textboxes, or you want an alternative way, try setting a simple global variable private int idCounter = 0;
and then every time you make a new textbox, you set its ID
to idCounter
, and call idCounter++;
immediately afterwards.
Upvotes: 2