Solved

How to access each datagrid item

Posted on 2008-09-29
38
422 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
ID: 22597415
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
ID: 22597416
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
ID: 22597425
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
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22597640
0
 
LVL 3

Expert Comment

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

Author Comment

by:will110
ID: 22597748
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
ID: 22597999
What is speakerschildNode2?
0
 

Author Comment

by:will110
ID: 22598092
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
ID: 22598130
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
ID: 22598216
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
ID: 22598357
is this winforms or asp.net? What version ov visual studio are you using?
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22598383
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
ID: 22598395
its is webform and I'm using vs2008
and columns in datagrid are bound columns..
0
 
LVL 22

Expert Comment

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

Author Comment

by:will110
ID: 22598525
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
ID: 22598558
Sorry, this:
TextBox speakerName = (TextBox)item.FindControl("txtSpeakerName");
Same to the other line.
 
0
 

Author Comment

by:will110
ID: 22598597
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
ID: 22598624
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
ID: 22598692
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
 

Author Comment

by:will110
ID: 22598940
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
ID: 22599006
Where is "SpeakeraddButton" defined? Within the DataGrid or outside the DataGrid?
0
 

Author Comment

by:will110
ID: 22599122
out side the datagrid
0
 
LVL 22

Expert Comment

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

Author Comment

by:will110
ID: 22599382
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
ID: 22599439
This is getting complicated. So this DataGrid is defined within another server control?
0
 

Author Comment

by:will110
ID: 22599513
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
ID: 22599620
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
ID: 22599621
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
ID: 22599644
Again, change "DataGrid1" to "SpeakersDataGrid" in your case.
0
 

Author Comment

by:will110
ID: 22599841
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
ID: 22599876
Does Item means one row in Datagrid?
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22599928
>>>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
ID: 22600008
It is still adding last row only :(
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
ID: 22600086
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
ID: 22600166
It worked!!!
 I moved
 XmlElement speakerschildNode2 = xmlDoc.CreateElement("Presenter"); into for loop
Thank You SOOOOOO MUCH
0
 

Author Closing Comment

by:will110
ID: 31501212
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
ID: 22600305
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
ID: 22600426
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
2 questions 10 25
Cant save 3D 4 19
C# winforms programmitically move panels 6 29
Firing an ASP.NET event on selection of a JQuery datepicker 4 16
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

770 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