[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# Get values of cells in a gridview

Posted on 2014-08-16
18
Medium Priority
?
2,937 Views
Last Modified: 2016-02-10
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

0
Comment
Question by:dodgerfan
17 Comments
 
LVL 7

Expert Comment

by:Camillia
ID: 40265788
If you're clicking on a row to save that row's data, then implement RowCommand.
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266088
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
 

Author Comment

by:dodgerfan
ID: 40266219
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
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266239
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
 

Author Comment

by:dodgerfan
ID: 40266253
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
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266265
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
 

Author Comment

by:dodgerfan
ID: 40266275
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
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266283
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
 

Author Comment

by:dodgerfan
ID: 40266303
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
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 40266304
You do select the complete row before clicking on the button, correct?
0
 

Author Comment

by:dodgerfan
ID: 40266305
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
 

Author Comment

by:dodgerfan
ID: 40266326
Doesn't this select the row: GridViewRow row = grdResults.SelectedRow;
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266336
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
 

Author Comment

by:dodgerfan
ID: 40266339
Just a standard asp.net web application, with c# code behind, using Visual Studio 2012.
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40266376
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
 
LVL 6

Expert Comment

by:Mandeep Singh
ID: 40267101
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
 

Author Closing Comment

by:dodgerfan
ID: 40268175
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

Featured Post

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.

Question has a verified solution.

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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Screencast - Getting to Know the Pipeline
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month19 days, 17 hours left to enroll

873 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