Solved

How to access each datagrid item

Posted on 2008-09-29
38
419 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:will110
  • 18
  • 14
  • 3
  • +2
38 Comments
 
LVL 26

Expert Comment

by:Anurag Thakur
Comment Utility
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
 
LVL 8

Expert Comment

by:MatthiasVance
Comment Utility
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
 
LVL 3

Expert Comment

by:Diveblue
Comment Utility
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
 
LVL 26

Expert Comment

by:Anurag Thakur
Comment Utility
0
 
LVL 3

Expert Comment

by:Diveblue
Comment Utility
fyi, mathias' answer refers to the windows forms control datgridVIEW, while mine refers to the asp.net datagrid
0
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
What is speakerschildNode2?
0
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
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
 
LVL 3

Expert Comment

by:Diveblue
Comment Utility
is this winforms or asp.net? What version ov visual studio are you using?
0
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
its is webform and I'm using vs2008
and columns in datagrid are bound columns..
0
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
Change "DataGrid1" to "SpeakersDataGrid" in your case. Also change "txtSpeakerName" and "txtSpeakerTitle" to your actual TextBox controls' ID's.
0
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
Sorry, this:
TextBox speakerName = (TextBox)item.FindControl("txtSpeakerName");
Same to the other line.
 
0
 

Author Comment

by:will110
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
Where is "SpeakeraddButton" defined? Within the DataGrid or outside the DataGrid?
0
 

Author Comment

by:will110
Comment Utility
out side the datagrid
0
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
Just want to confirm:
SpeakernameTextBox and  SpeakertitleTextBox3 are difined in the TemplateColumns of the DataGrid? Or outside the DataGrid?
0
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
This is getting complicated. So this DataGrid is defined within another server control?
0
 

Author Comment

by:will110
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
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
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
Again, change "DataGrid1" to "SpeakersDataGrid" in your case.
0
 

Author Comment

by:will110
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
Does Item means one row in Datagrid?
0
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
>>>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
 

Author Comment

by:will110
Comment Utility
It is still adding last row only :(
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
Comment Utility
Double check your logic to create the XML document.
Try move this line inside of foreach loop:
XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter");
0
 

Author Comment

by:will110
Comment Utility
It worked!!!
 I moved
 XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter"); into for loop
Thank You SOOOOOO MUCH
0
 

Author Closing Comment

by:will110
Comment Utility
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
 

Author Comment

by:will110
Comment Utility
Hello Prairiedog

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

Thank you


0
 
LVL 22

Expert Comment

by:prairiedog
Comment Utility
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now