How to access each datagrid item

Hello Experts,

I need to access each item in datagrid using C#
Is there something like datagrid1.items[0][0] which should get me item in 1st row and 1st column
Thank You
will110Asked:
Who is Participating?
 
prairiedogConnect With a Mentor Commented:
Double check your logic to create the XML document.
Try move this line inside of foreach loop:
XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter");
0
 
Anurag ThakurTechnical ManagerCommented:
silly question to ask but still asking
why do you want to loop a datagrid
why dont you loop your datasource for your data grid that might be more efficient and simpler
0
 
MatthiasVanceCommented:
You could do the following to get the value on row 0 col 0.

Kind regards,

Matthias Vance
DataGridView1.Rows[0].Cells[0].Value

Open in new window

0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
DiveblueCommented:
depends on whether you are looking at a bound column or a templated column....here's a decent explanation....
http://www.dotnetjunkies.com/Tutorial/FFFA1157-CE39-406A-BD0C-7EF3188A91F7.dcik
it mostly refers to SelectedItem, but you can replace that with Items(x)
0
 
Anurag ThakurTechnical ManagerCommented:
0
 
DiveblueCommented:
fyi, mathias' answer refers to the windows forms control datgridVIEW, while mine refers to the asp.net datagrid
0
 
will110Author Commented:
They are databound columns and I'm trying this FOR loop can you help me out

 for (int i = 0; i <= SpeakersDataGrid.Items.Count - 1; i++)
                    {
                        speakerschildNode2.SetAttribute("Name", SpeakersDataGrid.Items[0].Cells[i].Text);
                        speakerschildNode2.SetAttribute("Title", SpeakersDataGrid.Items[0].Cells[i+1].Text);
                    }
I'm try to acheive this
<speaker>
 <Name: abc Title :xyz />
<Name: aaa Title:xyz/>
</speakers>
0
 
prairiedogCommented:
What is speakerschildNode2?
0
 
will110Author Commented:
its is childnode
Speakers is parent node
Speaker is child node which has two attributes Name and Title

so the  XML file looks like
<Speakers>
<Speaker Name: abc Title:xxx />
<Speaker Name :aaa Title:yyy/>
.
.Goes on till all the rows in datagrid are completed
.</Speaker>
0
 
prairiedogCommented:
So you want to loop through the DataGrid and save those information to an XML file?
Maybe you can explain a little bit more about what you are trying to do so we can better help you.
0
 
will110Author Commented:
Ya I'm trying to Loop through Datagrid and save that information to a XMLfile..

I have two textboxes on a page for entering Name and Title of Speaker
when user enters them and press add button the name and title are shown in a datagrid
User can enter N number of speaker name and titles
all the N number entered by user are shown in datagrid
So Now we have N rows in data grid with 2 columns(Name and Title)

now finally there is a button on page called BuildXML and when user clicks it the data in datagrid should be saved as XML file as shown below

<Speakers>
<Speaker Name: abc Title:xxx />
<Speaker Name :aaa Title:yyy/>
.
.
.Goes on N times till all the rows in datagrid are completed
.</Speaker
0
 
DiveblueCommented:
is this winforms or asp.net? What version ov visual studio are you using?
0
 
prairiedogCommented:
Instead of using "for" loop, you will need to use "foreach" loop like this:
 

protected void BuildXML_Click(object sender, EventArgs e)
{
	foreach (DataGridItem item in this.DataGrid1.Items)
	{
		TextBox speakerName = item.FindControl("txtSpeakerName");
		TextBox speakerTitle = item.FindControl("txtSpeakerTitle");
		// Build your XML with speakerName.Text and speakerTitle.Text
	}
}

Open in new window

0
 
will110Author Commented:
its is webform and I'm using vs2008
and columns in datagrid are bound columns..
0
 
prairiedogCommented:
Change "DataGrid1" to "SpeakersDataGrid" in your case. Also change "txtSpeakerName" and "txtSpeakerTitle" to your actual TextBox controls' ID's.
0
 
will110Author Commented:
I'm getting this Error
Error      1      Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.TextBox'. An explicit conversion exists (are you missing a cast?)      

at this line of code
TextBox speakerName = item.FindControl("txtSpeakerName");
0
 
prairiedogCommented:
Sorry, this:
TextBox speakerName = (TextBox)item.FindControl("txtSpeakerName");
Same to the other line.
 
0
 
will110Author Commented:
If my datagrid is as below

          Name     Title
         Joe           Sr
        Sam          Sr
        Chris         Jr

and my code to loop through datagrid items and save to XML file is
 foreach(DataGridItem item in this.SpeakersDataGrid.Items )
                    {
                        TextBox speakerName = item.FindControl("SpeakernameTextBox");
                        TextBox speakerTitle = item.FindControl("speakerTitle");
                        speakerschildNode2.SetAttribute("Name", speakerName.Text);
                        speakerschildNode2.SetAttribute("Title", speakerTitle.Text);
                    }
will I be able to achive
<Speakers>
<Speaker Name:Joe Title:Sr />
<Speaker Name:Sam Title:Sr/>
<Speaker Name:Chris Title :Jr/>
</Speakers>
0
 
will110Author Commented:
I'm getting this error after adding (Textbox)

Error      1      The type or namespace name 'Textbox' could not be found (are you missing a using directive or an assembly reference?)      

at this line  
 TextBox speakerName = (Textbox)item.FindControl("SpeakernameTextBox");
0
 
prairiedogCommented:
C# is case-sensitive. TextBox is not the same as Textbox
You mentioned that there are two text boxes for Name and Title, so I assume they are TextBox controls in TemplateColumn, right? My sample code is based on the assumption.
0
 
will110Author Commented:
This code is not writting datagrid items to XML file

This is what I'm doing
Below code adds text entered in the text boxes to speakersdata grid

protected void SpeakeraddButton_Click(object sender, EventArgs e)
        {
            DataTable dt;
            dt = (DataTable)Session["SpeakersDataGrid"];
            DataRow dr = dt.NewRow();
            dr["Speakername"] = SpeakernameTextBox.Text;
            dr["Title"] = SpeakertitleTextBox3.Text;            
            dt.Rows.Add(dr);
            dt.AcceptChanges();
            SpeakersDataGrid.DataSource = dt;
            SpeakersDataGrid.DataBind();
            Session["SpeakersDataGrid"] = dt;
            SpeakernameTextBox.Text = "";
            SpeakertitleTextBox3.Text = "";        

        }

Now that the datagrid is ready with data I need to write it to XML file and code I'm using is


                  XmlElement speakerschildNode1 = xmlDoc.CreateElement("Speakers");
                    XmlElement speakerschildNode2 = xmlDoc.CreateElement("Speaker");
                    foreach(DataGridItem item in this.SpeakersDataGrid.Items )
                    {
                        TextBox speakerName = (TextBox)item.FindControl("SpeakernameTextBox");
                        TextBox speakerTitle = (TextBox)item.FindControl("SpeakertitleTextBox3");
                        speakerschildNode2.SetAttribute("Name", speakerName.Text);
                        speakerschildNode2.SetAttribute("Title", speakerTitle.Text);
                    }
                    root.AppendChild(speakerschildNode1);
                    speakerschildNode1.AppendChild(speakerschildNode2);
                   

But this code is not working

0
 
prairiedogCommented:
Where is "SpeakeraddButton" defined? Within the DataGrid or outside the DataGrid?
0
 
will110Author Commented:
out side the datagrid
0
 
prairiedogCommented:
Just want to confirm:
SpeakernameTextBox and  SpeakertitleTextBox3 are difined in the TemplateColumns of the DataGrid? Or outside the DataGrid?
0
 
will110Author Commented:
They are defined outside the datagrid and below is the code

<ContentTemplate>
<asp:DataGrid id="SpeakersDataGrid" runat="server" AutoGenerateColumns="False"
                cellpadding="5" width="100%" AllowPaging="True" PageSize ="5" >
    <AlternatingItemStyle Font-Underline="False" Font-Size="11px"
                    Font-Names="verdana"  ForeColor="Black"  BackColor="#EBEBEB">
    </AlternatingItemStyle>
    <Columns>
        <asp:BoundColumn DataField ="Speakername" SortExpression="Speakername" HeaderText ="Speaker Name"></asp:BoundColumn>
        <asp:BoundColumn DataField ="Title" SortExpression="Title" HeaderText ="Title"></asp:BoundColumn>
    </Columns>
    <HeaderStyle Font-Underline="False" Font-Size="10px" Font-Names="verdana" Font-Bold="True" ForeColor="White"  BackColor="#333333"/>
    <ItemStyle Font-Underline="False" Font-Size="11px" Font-Names="verdana"  
                    ForeColor="Black"  BackColor="White"/>
    <PagerStyle Mode="NumericPages" />
    </asp:DataGrid>
<br />
<asp:Label ID="Label14" runat="server" Text="Speaker Name:"></asp:Label>
<asp:TextBox ID="SpeakernameTextBox" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label15" runat="server" Text="Speaker Title:"></asp:Label>
<asp:TextBox ID="SpeakertitleTextBox3" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="SpeakeraddButton" runat="server" Text="Add"
        onclick="SpeakeraddButton_Click" />
              </ContentTemplate>


0
 
prairiedogCommented:
This is getting complicated. So this DataGrid is defined within another server control?
0
 
will110Author Commented:
ya it is inside a tab control

 <cc2:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel2">
<HeaderTemplate >
Speakers
 </HeaderTemplate>
<ContentTemplate>
<asp:DataGrid id="SpeakersDataGrid" runat="server" AutoGenerateColumns="False"
                cellpadding="5" width="100%" AllowPaging="True" PageSize ="5" >
    <AlternatingItemStyle Font-Underline="False" Font-Size="11px"
                    Font-Names="verdana"  ForeColor="Black"  BackColor="#EBEBEB">
    </AlternatingItemStyle>
    <Columns>
        <asp:BoundColumn DataField ="Speakername" SortExpression="Speakername" HeaderText ="Speaker Name"></asp:BoundColumn>
        <asp:BoundColumn DataField ="Title" SortExpression="Title" HeaderText ="Title"></asp:BoundColumn>
    </Columns>
    <HeaderStyle Font-Underline="False" Font-Size="10px" Font-Names="verdana" Font-Bold="True" ForeColor="White"  BackColor="#333333"/>
    <ItemStyle Font-Underline="False" Font-Size="11px" Font-Names="verdana"  
                    ForeColor="Black"  BackColor="White"/>
    <PagerStyle Mode="NumericPages" />
    </asp:DataGrid>
<br />
<asp:Label ID="Label14" runat="server" Text="Speaker Name:"></asp:Label>
<asp:TextBox ID="SpeakernameTextBox" runat="server"></asp:TextBox>

<br />
<br />
<asp:Label ID="Label15" runat="server" Text="Speaker Title:"></asp:Label>

<asp:TextBox ID="SpeakertitleTextBox3" runat="server"></asp:TextBox>

<br />
<br />
<asp:Button ID="SpeakeraddButton" runat="server" Text="Add"
        onclick="SpeakeraddButton_Click" />
 </ContentTemplate>
</cc2:TabPanel>

Thats all the code for tab called Speakers
0
 
will110Author Commented:
can you tell me how to access a item in bound column of a datagrid in a web application

say datagrid has

  col1 col2
  aa    bb
  cc    ddd

how to access aa item that will solve my problem
0
 
prairiedogCommented:
Change the foreach loop to this:
foreach (DataGridItem item in this.DataGrid1.Items)
{
	string speakerName = item.Cells[0].Text;
	string speakerTitle = item.Cells[1].Text;
	speakerschildNode2.SetAttribute("Name", speakerName);
	speakerschildNode2.SetAttribute("Title", speakerTitle);
}

Open in new window

0
 
prairiedogCommented:
Again, change "DataGrid1" to "SpeakersDataGrid" in your case.
0
 
will110Author Commented:
Guess We are almost there
The below code is generating XML file but with only one pair of speakername and title which is last row in the datagrid.
XmlElement speakerschildNode1 = xmlDoc.CreateElement("Presenters");
                    XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter");
                   foreach(DataGridItem item in this.SpeakersDataGrid.Items )
                    {
                        string speakerName = item.Cells[0].Text;
                        string speakerTitle = item.Cells[1].Text;
                        speakerschildNode2.SetAttribute("Name", speakerName);
                        speakerschildNode2.SetAttribute("Title", speakerTitle);
                     }
                   root.AppendChild(speakerschildNode1);
                   speakerschildNode1.AppendChild(speakerschildNode2);

Is there some thing where I made a mistake?
0
 
will110Author Commented:
Does Item means one row in Datagrid?
0
 
prairiedogCommented:
>>>Is there some thing where I made a mistake?
Yes, you logic is wrong. In the foreach loop the last two lines are overwriting your previous values because you didn't append them to the speakersChildNode1.
Try this:
foreach(DataGridItem item in this.SpeakersDataGrid.Items )
                    {
                        string speakerName = item.Cells[0].Text;
                        string speakerTitle = item.Cells[1].Text;
                        speakerschildNode2.SetAttribute("Name", speakerName);
                        speakerschildNode2.SetAttribute("Title", speakerTitle);
                     root.AppendChild(speakerschildNode1);
                   speakerschildNode1.AppendChild(speakerschildNode2);

                     }
                   
0
 
will110Author Commented:
It is still adding last row only :(
0
 
will110Author Commented:
It worked!!!
 I moved
 XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter"); into for loop
Thank You SOOOOOO MUCH
0
 
will110Author Commented:
Thank You Very Much for you solution..I never came across an expert who has such good  patience like you  to solve the problem. Thank You once again..You  Rock!!
0
 
will110Author Commented:
Hello Prairiedog

Do you have any any simple solution to give Edit and Delete options to every row in Datagrid.

Thank you


0
 
prairiedogCommented:
It depends on your requirements. If you just need to update the Speaker's Name and Title, it should be easy to implement, but it will be a new question. Please post a new question so all experts will be able to see it and help you to get the solution.
0
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.

All Courses

From novice to tech pro — start learning today.