Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to add all text box data to datagridview i am new in c#.net, i m doing as follows,
C#
dataGridView1.Rows[1].Cells[1].Value = textBox1.Text;
dataGridView1.Rows[2].Cells[2].Value = textBox2.Text;
dataGridView1.Rows[3].Cells[3].Value = textBox3.Text;
dataGridView1.Rows[4].Cells[4].Value = textBox4.Text;


but i want to use loop for this but problem is how to suffix i by repalcing number tn textbox name i.e how to replace 1 in textbox1.text by textbox[i].text or (textbox+i+).text
please help
C#
for(int i=0;i<4;i++)
{
    dataGridView1.Rows[i].Cells[i].Value = textBox[i].Text;
}
Posted
Updated 4-Oct-15 23:22pm
v5
Comments
Sinisa Hajnal 5-Oct-15 2:40am    
Why not just create editable grid which will take care of the controls automatically? You can even do a repeater and set the template to whatever you want (including textboxes)

Step1: Add all textboxes inside a panel. Here is the code:

In ASPX
ASP.NET
<asp:panel id="pnlTextBoxes" runat="server" xmlns:asp="#unknown">
	<asp:textbox id="textBox1" runat="server" />
	<asp:textbox id="textBox2" runat="server" />
	<asp:textbox id="textBox3" runat="server" />
	<asp:textbox id="textBox4" runat="server" />
</asp:panel>

Step2: In this step you need to add code in your *.aspx.cs page. Here is the code:

In Code-behind
C#
for(int i=1;i<=4;i++)
{
	TextBox txtInstance = (TextBox)pnlTextBoxes.FindControl("textBox" + i);
	if(txtInstance != null)
	{
		dataGridView1.Rows[i].Cells[i].Value = txtInstance.Text;
	}
}
 
Share this answer
 
v2
Comments
Member 11922776 5-Oct-15 4:39am    
this is a winform application
C#
var txts = new List<TextBox>(){ textBox1, textBox2, textBox3, textBox4 };
for(int i=0;i<3;i++)//if i=0 then it must be <3
{
    dataGridView1.Rows[i].Cells[i].Value = txts[i].Text;
}


-KR
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900