How to get a specific column value from a DataTable in c#
I have a problem with my code C#.
I need read a specific column value from a DataTable.
I've tried using this solution without success, because the output is the name of column selected in the query (File) and not the value of field database.
I would greatly appreciate any help you can give me in working this problem.
Here is my code:
public DataTable GridViewBind()
{
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";
using (OdbcDataAdapter command =
new OdbcDataAdapter(sql1, cn))
{
try
{
cn.Open();
dset = new DataSet();
dset.Clear();
command.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Write(dt.Columns[0].ToString());
return dt;
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
if (command != null)
{
command.Dispose();
}
if (cn != null)
{
cn.Close();
cn.Dispose();
}
}
}
}
}
Edit #1
Now I have error:
System.IndexOutOfRangeException: There is no row at position 0.
public DataTable GridViewBind()
{
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";
using (OdbcDataAdapter command =
new OdbcDataAdapter(sql1, cn))
{
try
{
cn.Open();
dset = new DataSet();
dset.Clear();
command.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
string file = dt.Rows[0].Field<string>(0);
Response.Write(file.ToString());
return dt;
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
if (command != null)
{
command.Dispose();
}
if (cn != null)
{
cn.Close();
cn.Dispose();
}
}
}
}
}
The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
This is pretty simple to achieve. From the DataTable, first we can apply the Select function to get only the row that is associated with Id=1.
After that, we can do the CopyToDataTable() function so as to get it in the DataTable format.
Since, we are expecting that there is only row for Id=1, we can directly apply Rows[0] and then give the column name, convert to string and assign to file variable.
string file = dt.Select("Id=1").CopyToDataTable().Rows[0]["FILE"].ToString()
Note that if you are selecting string value, you need to apply single quotes. For eg, if Id is of string type, then you need to apply like below.
Id='1'
Related
I have a table and I want to get specific column from my dataset my table only has one row.
Here is my code
private DataSet Ds = new DataSet();
public DataSet GetDataSet(string Query)
{
try
{
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
MySqlDataAdapter Da = new MySqlDataAdapter(Query, conn);
Da.Fill(Ds);
conn.Close();
}
}
catch (Exception) { }
return Ds; //See image
}
public string getDataCellString(string headerName)
{
return "";//I want to get cell from heder name
}
Here is my question: How can I get a cell value from a header name?
If you only have one row you can:
public string getDataCellString(string headerName)
{
return Ds.Tables[0].Rows[0][headerName].ToString();
}
`Ds.Tables[0].Rows[0]["headerName"].ToString();
I've got a dropdown whose values are retrieved from a database. I am retrieving ID and name from the database.
public void GetDepartment_temp()
{
try
{
DataTable dt = new DataTable();
listBoxDepartment.ClearSelection();
Get_Department objDAL = new Get_Department();
dt = objDAL.Get_Hospital_Department();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
listBoxDepartment.Items.Add(new ListItem(row["department_name"].ToString(), row["department_id"].ToString()));
}
}
}
catch (Exception) { }
}
I've got to show the number of employees of each department in the text box. Suppose a user selects human department, then the text box should display the number of employees in that department.
For the ListBox, only two values from the database can be retrieved. How can I show the number of employee in this condition?
public DataTable Get_Hospital_Department()
{
try
{
DataTable dt = new DataTable();
dt = DbAccessHelper.ExecuteDataSet("p_get_hospital_department", true).Tables[0];
return dt;
}
catch (Exception) { return null; }
}
CREATE PROCEDURE [dbo].[p_get_hospital_department]
AS
BEGIN
SET NOCOUNT ON;
SELECT department_id
,department_name
FROM [dbo].[tbl_hospital_department];
END
The statement For the ListBox, only two values from the database can be retrieved. is not correct. You can populate the datatable with as many fields as you want. However, you can set only the Value and text attributes of the Listbox item as you have done.
Change the stored procedure code to fetch the employee count also.
Mark your datatable dt as static and public.
Fetch the datable and you can play with the data as you want. You can fetch the employee count in the textbox on listview selected index changed as shown below:
public static DataTable dt = new DataTable();
public void GetDepartment_temp()
{
try
{
string connString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command =
new SqlCommand(
"select Department.DepartmentID, Department.[Department Name], count( Department.DepartmentID) as empCount from Department join Employee on Department.DepartmentID = Employee.DepartmentID group by Department.DepartmentID, Department.[Department Name]",
connection);
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
dt.PrimaryKey = new DataColumn[] {dt.Columns["DepartmentID"]};
ListBox1.ClearSelection();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
ListBox1.Items.Add(new ListItem(row["Department Name"].ToString(),
row["DepartmentID"].ToString()));
}
}
}
catch (Exception ex)
{
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRow dr = dt.Rows.Find(Convert.ToInt32(ListBox1.SelectedItem.Value));
TextBox5.Text = dr["empCount"].ToString();
}
Where can i put an if-statement saying that: if the sql query comes back empty, then Console.WriteLine("I'm sorry, empty...whatnot");
I don't know how to check to see if the result of the query is empty.
This is my code:
public void IsMovieInStore()
{
Console.Write("Searh for a movie title: ");
string title = Console.ReadLine();
string connectionString = #"Data Source=|DataDirectory|\VideoStoreDB.sdf";
SqlCeConnection connection = new SqlCeConnection(connectionString);
SqlCeCommand command = new SqlCeCommand("SELECT Movie.Title, MovieHandler.InStore FROM Movie INNER JOIN MovieHandler ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable WHERE MovieHandler.InStore = 1 AND Movie.Title = #title", connection);
command.Parameters.AddWithValue("#title", title);
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Movie");
foreach (DataTable dataTable in dataSet.Tables)
{
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
Console.WriteLine(column.ColumnName + ": " + row[column]);
}
Console.WriteLine("-------------------------");
}
}
Console.ReadLine();
}
You can easily check this by assigning dataAdapter.Fill(dataSet, "Movie"); to an int variable. The Fill method returns the number of rows that are added to or refreshed in the dataset. See msdn for more information: DataAdapter.Fill Method.
int rows = dataAdapter.Fill(dataSet, "Movie");
if(rows > 0)
{
//process data
}
else
{
Console.WriteLine("Sorry, no data...");
}
try checking table and row counts
//....
dataAdapter.Fill(dataSet, "Movie");
if (0 == dataSet.Tables.Count || 0 == dataSet.Tables[0].Rows.Count)
{
Console.WriteLine("I'm so lonely");
}
foreach (DataTable dataTable in dataSet.Tables)
//...
You dont need to use dataset, use datatable:
public void IsMovieInStore()
{
Console.Write("Searh for a movie title: ");
string title = Console.ReadLine();
string connectionString = #"Data Source=|DataDirectory|\VideoStoreDB.sdf";
SqlCeConnection connection = new SqlCeConnection(connectionString);
SqlCeCommand command = new SqlCeCommand("SELECT Movie.Title, MovieHandler.InStore FROM Movie INNER JOIN MovieHandler ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable WHERE MovieHandler.InStore = 1 AND Movie.Title = #title", connection);
command.Parameters.AddWithValue("#title", title);
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
If(dataTable != null && dataTable.Rows.Count>0)
{
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
Console.WriteLine(column.ColumnName + ": " + row[column]);
}
Console.WriteLine("-------------------------");
}
}
}
else{
Console.WriteLine("Empty result");
}
Console.ReadLine();
}
I'm working on a project which uses an Access database. First of all I copy the information that i need from db and put it in a DataTable (with combining 2 tables). Over this datatable I search items; update, delete, add rows using a GridView and all of that happens in an ajax update panel.
Problem occurs when i try to apply the changes back to the db. What i want to do is get certain rows of the DataTable and update/insert/delete them to certain rows of certain tables. Important thing is database table has to contain the same information as the DataTable.
İ actually don't know if I can use the OledbDataAdapter.Update this way.
Here is the exeption that i get : Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
My Code:
void load_dtTable()
{
OleDbConnection bag = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Profiles\\StjBugraO\\Desktop\\data.accdb");
DataTable dtResult = new DataTable();
if (Session["dtResult"] != null)
{
dtResult = (DataTable)Session["dtResult"];
}
else
{
bag.Open();
try
{
OleDbDataAdapter adtr = new OleDbDataAdapter("select gt.NodeID, gt.unit_num,gt.unit_name_text,gt2.ip_id ,gt2.server_name_text ,gt.call_flow_type From gt inner join gt2 on gt.cm_id=gt2.cm_id", bag);
dtResult.Clear();
adtr.Fill(dtResult);
adtr.Dispose();
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "Şube Kodu";
dtResult.Columns[2].ColumnName = "Şube ADI";
dtResult.Columns[3].ColumnName = "IP Adresi";
dtResult.Columns[4].ColumnName = "Call Manager";
dtResult.Columns[5].ColumnName = "Santral Tipi";
foreach (DataRow dr in dtResult.Rows)
{
if ((string)dr[5] == "P")
{
dr[5] = "PRI";
}
else if ((string)dr[5] == "A") dr[5] = "ANALOG";
}
}
catch (Exception e)
{
}
Session["dtResult"] = dtResult as DataTable;
bag.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
DataTable dtResult = Session["dtResult"] as DataTable;
//changing the names of the columns (that i need) to be the same with the db
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "unit_num";
dtResult.Columns[2].ColumnName = "unit_name_text";
dtResult.Columns[3].ColumnName = "ip_id";
dtResult.Columns[5].ColumnName = "call_flow_type";
OleDbConnection bag = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Profiles\\StjBugraO\\Desktop\\data.accdb");
OleDbDataAdapter adtr2 = new OleDbDataAdapter("select NodeID ,unit_num ,unit_name_text , ip_id , call_flow_type from gt", bag);
OleDbCommandBuilder Ocmd = new OleDbCommandBuilder(adtr2);
adtr2.DeleteCommand=Ocmd.GetDeleteCommand();
adtr2.InsertCommand=Ocmd.GetInsertCommand();
adtr2.UpdateCommand=Ocmd.GetUpdateCommand();
DataTable dt = dtResult.GetChanges();
int updates = 0;
try
{
if(dt != null)
updates=adtr2.Update(dtResult);
}
catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
//changing them back
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "Şube Kodu";
dtResult.Columns[2].ColumnName = "Şube ADI";
dtResult.Columns[3].ColumnName = "IP Adresi";
dtResult.Columns[4].ColumnName = "Call Manager";
dtResult.Columns[5].ColumnName = "Santral Tipi";
Label2.Text = updates + "changes applied.";
adtr2.Dispose();
bag.Close();
}
how can i do multiple update using datatable ?
i found this Update 1 row
my code:
public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne);
//Update all lines, it not save in Database
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
the problem is :
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
it not save it into database.
Thanks you in advance,
Stev
You need to first set the UpdateCommand property on the DataAdapter to the UPDATE statement that will be executed to update a row in the database.
Then, after updating values in the DataTable, you need to pass it to DataAdapter.Update().
This will then execute the UpdateCommand for each updated row in the DataTable.
References:
MSDN - SqlDataAdapter.Update
MSDN - SqlDataAdapter.UpdateCommand
You are updating the value in-memory. The DataTable class is not a sql view, but a memory representation. The Sql Data Adapter only copy the data.
You have to write back the changes to the DB. Try this :
public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn);
da.UpdateCommand = connectedConnection.CreateCommand();
da.UpdateCommand.XXXX = YYYY; // construct the SQL Command
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne);
//Update all lines, it not save in Database
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
da.Update(dt);
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
This should works.
You will have to call da.Update()