C# Get values of cells in a gridview

I have a gridview that is bound to a table. The code is in C#, with the table in a MongoDB. The code returns the record from the database and displays in a gridview. I need to take the values displayed and insert them into a SQL server table. How can I get the values from thee gridview cells? The code I have so far is below from the code behind page:

using System; 
using System.Coliections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Data.SqIClient; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using MongoDB.Bson; 
using MongoDB.Driver; 
using MongoDB.Driver.Builders; 

namespace MyWebSite 
{ 
public partial class FindEmployee : System.Web.UI.Page { 
protected void Page_Load(object sender, EventArgs e) 
{ 
} 

public class DataFromDB 
{ 
public string COMP { get; set; } 
public string FIRST_NAME { get; set; } 
public string LAST_NAME { get; set; } 
public string MIDDLE_NAME { get; set; } 
public string SSN { get; set; } 
} 


protected void ConnectMongoDB() 
{ 
var connectionString = "mongodb://test"; 
var client = new MongoClient(connectionString); 
var server = client.GetServer(); 
var database = server.GetDatabase("db"); 
var collection = database.GetColiection<LazyBsonDocument>("entity_map"); 
var inserted = tbSSN.Text.ToStringO; 
var q = Query.Matches("SSN.data", "^" + inserted + ".*"); 
 
String[] String Names = new String[] { "COMP", "FIRST_NAME", "LAST_NAME", "MIDDLE_NAME", "SSN" }; 
List<DataFromDB> mdfdblist = new List<DataFromDB>(); 
foreach (var doc in collection.Find(q)) { 
DataFromDB mdfdb = new DataFromDBO; 
using (doc) 
{ 
foreach (var stringName in StringNames) 
{ 
if (doc.Contains(stringName)) { 
var data = doc[stringName]; 
foreach (var subDoc in data.AsBsonArray) 
{ 
string value = subDoc["data"].AsString; switch (stringName) 
{ 
case "COMP": mdfdb.COMP = value; 
break; 
case "FIRST NAME": mdfdb.FIRST _NAME = value; 
break; 
case "LAST NAME": mdfdb.LAST _NAME = value; 
break; 
case "MIDDLE_NAME": mdfdb.MIDDLE_NAME = value; break; 
case "SSN": 
mdfdb.SSN = value; 
break; 
} 
} 
} 
} 
} 
mdfdblist.Add(mdfdb ); 
} 
grdResults.DataSource = mdfdblist; 
grdResults.DataBind(); 
grdResultsVisible = true; 
} 
 
protected void GetEmpData(){ 
var connect = ConfigurationManager.ConnectionStrings[,"'].ToStringO; 
var proc = "splnsertEmp"; 
using (var conn = new SqIConnection(connect)) { 
using (var cmd = new SqICommand(proc, conn)) 
{ 
cmd.CommandType = CommandType.StoredProcedure; 
cmd.Parameters.AddWithValue("@COMP", ); 
cmd.Parameters.AddWithValue("@FIRST_NAME", )); 
cmd.Parameters.AddWithValue("@LAST_NAME", )); 
cmd.Parameters.AddWithValue("@MIDDLE_NAME", )); 
cmd.Parameters.AddWithValue("@SSN", )); 
conn.Oper(); 
cmd. ExecuteNonOueryO; 
} 
} 
} 

protected void btnFind_Click(object sender, EventArgs e) { 
ConnectMDB() 
} 
protected void btnSave_Command(object sender, System. Web. U I. WebControls. Command EventArgs e) 
{ 
GetEmpData(); 
} 
}
}

Open in new window

dodgerfanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CamilliaCommented:
If you're clicking on a row to save that row's data, then implement RowCommand.
0
Fernando SotoRetiredCommented:
Hi dodgerfan;

The variable mdfdblist is a List<DataFromDB> and contains all the information that is displayed in the DataGrid. If you are adding all the data from the DataGrid then all you need to do is loop through the mdfdblist and use that to create your SQL insert statement.
0
dodgerfanAuthor Commented:
Most of the time, 1 record will be returned. Once is a while it may be several records, which is why I have the button in the row for each record. I want just the data fro the selected row. Can I loop through it that way? And how can I implement the RowCommand?
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Fernando SotoRetiredCommented:
There is a property on the GridView called SelectedRow. So select the row you wish to insert into SQL server and then click on the button. In the button click event you get a reference to the selected row as follows:

GridViewRow row = grdResults.SelectedRow;

Then you can access the data of the row like row.Cells[ I ] where i is the index of the column you wish to get.
0
dodgerfanAuthor Commented:
I have tried this but get an error: Object reference not set to an instance of an object. That comes on the  string lname line. I did a response write just to see if it will return the value I need. Am I missing something?

protected void btnSave_Command(object sender, System.Web.UI.WebControls.Command EventArgs e)
{
GridViewRow row = grdResults.SelectedRow;
string lname = grdResults.SelectedRow.Cells[3].Text;

Response.Write(lname);
}
0
Fernando SotoRetiredCommented:
Hi dodgerfan;

In the below code this line gives you a reference to the row, GridViewRow row = grdResults.SelectedRow;, then the second line should use that reference to access the Cells as shown below.
protected void btnSave_Command(object sender, System.Web.UI.WebControls.Command EventArgs e) 
{ 
    GridViewRow row = grdResults.SelectedRow;
    string lname = row.Cells[3].Text;

    Response.Write(lname);
}

Open in new window

0
dodgerfanAuthor Commented:
Again, thanks for the help. I am still getting the Object reference not set to an instance of an object error, even after putting in your last code update. I've tried changing the button from OnCommand to OnClick, too. It's not returning anything but the error.
0
Fernando SotoRetiredCommented:
Place a breakpoint on this line of code, string lname = row.Cells[3].Text;, and then run the app again. When the app stops look at the value in row to make sure it is not null. Then if that is not null look at Cells[3] to see if that is null.
0
dodgerfanAuthor Commented:
The value is null for the row. When I try to step through the code it gives the object reference error.

The code is in the OnClick of a button:

protect void btnSave_Click(object sender, EventArgs e)
{
GridViewRow row = grdResults.SelectedRow;
string lname = row.Cells[3].Text;

Response.Write(lname);
}

The button is in a template field in the gridview on the aspx page:

<asp:Gridview ID="grdResults" runat="server" AutoGenerateColumns="false>
<columns>
<asp:BoundField DataField="COMP" />
<asp:BoundField DataField="FIRST_NAME" />
<asp:BoundField DataField="LAST_NAME" />
<asp:BoundField DataField="MIDDLE_NAME />
<asp:BoundField DataField="SSN" />
<asp:TemplateFIeld />
<ItemTemplate>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
</ItemTemplate>
</columns>
</asp:GridView>
0
Fernando SotoRetiredCommented:
You do select the complete row before clicking on the button, correct?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dodgerfanAuthor Commented:
I'm not sure what you mean? How do I do that? So the answer must be no. When I click the Save button I need to somehow select the row first before trying to get cell values?
0
dodgerfanAuthor Commented:
Doesn't this select the row: GridViewRow row = grdResults.SelectedRow;
0
Fernando SotoRetiredCommented:
No, it gets the selected row.

What type of Web application are you using ? I am trying to find a sample on the web so I can see how to select the row.
0
dodgerfanAuthor Commented:
Just a standard asp.net web application, with c# code behind, using Visual Studio 2012.
0
Fernando SotoRetiredCommented:
You need to add another column to the Grid which will have a button in it which once clicked it will highlight and select the entire row. Please see below link for three different options to add this column.

Allowing Users to Select Items in a DataGrid Web Server Control
0
Mandeep SinghDatabase AdministratorCommented:
Hi,

Use this link http://hightechnology.in/how-to-store-gridview-data-in-sql-server-database-row-by-row-basis/. It will save gridview data on row by row basis in SQL Server.
0
dodgerfanAuthor Commented:
Thanks for the help. I got it. Once you mentioned making sure I was selecting the row, I went back and was able to get it working. I'm using row_rommand and the code change I need was here:
It looks like this now:
int index = Convert.ToInt32(e.CommandArgument);
GridView row = grdResults.Rows[index];

I can then get the cell value for each cell, which I then use in the stored procedure to insert into a table. It works well. Thanks again for the help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

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.