I'm getting an error when retrieving data from the child row. Basically I need the lecturerName from tbl_lecturer, projectTitle from tbl_lecturer_project.
Here is my code.
//get data from 3 tables
DataSet ds = new DataSet(); // .xsd file name
DataTable dt = new DataTable();
//Connection string replace 'databaseservername' with your db server name
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapter;
con.Open();
//Stored procedure calling. It is already in sample db.
string selectSQL = "SELECT * FROM tbl_allocated_project where allocatedGroupId='" + team + "'";
cmd = new SqlCommand(selectSQL, con);
ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "tbl_allocated_project");
cmd.CommandText = "SELECT * FROM tbl_lecturer_project";
adapter.Fill(ds, "tbl_lecturer_project");
cmd.CommandText = "SELECT * FROM tbl_lecturer";
adapter.Fill(ds, "tbl_lecturer");
DataRelation dr1 = new DataRelation("dr1", ds.Tables["tbl_lecturer"].Columns["lecturerId"],ds.Tables["tbl_lecturer_project"].Columns["lecturerId"]);
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]);
ds.Relations.Add(dr1);
ds.Relations.Add(dr2);
foreach (DataRow row in ds.Tables["tbl_allocated_project"].Rows)
{
lblDisplay.Text = "";
//lblDisplay.Text += row["allocatedGroupId"];
//lblDisplay.Text += " " + row["intro"];
foreach (DataRow col in row.GetChildRows(dr2))
{
DataRow rowdata = col.GetParentRows(dr1)[0];
//lblDisplay.Text += " ";
lblDisplay.Text += rowdata["projectTitle"];
}
}
I'm getting this error:
GetChildRows requires a row whose table is tbl_lecturer_project, but the specified row's table is tbl_allocated_project.
Please help.
Should this:
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]);
be this:
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_allocated_project"].Columns["lecturerProjectId"], ds.Tables["tbl_lecturer_project"].Columns["allocatedProjectId"]);
This would make tbl_allocated_project the parent of tbl_lecturer_project, which should allow you to call GetChildRows on it.
Related
I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;
private void InsertExcelRecords(string filepath)
{
ExcelConn(filepath);
OleDbCommand Ecom = new OleDbCommand(Query, Econ);
Econ.Open();
DataTable dtSheet = Econ.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
if (!sheetName.EndsWith("$"))
continue;
Query = string.Format("select * from [" + sheetName + "]");
DataSet ds=new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable Exceldt = ds.Tables[0];
using (SqlConnection con = new SqlConnection(strConnString))
{
//connection();
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
//assigning Destination table name
objbulk.DestinationTableName = "tblCompany";
//Mapping Table column
objbulk.ColumnMappings.Add("Company", "CompanyName");
objbulk.ColumnMappings.Add("Contact Telephone", "CompanyContactNumber");
objbulk.ColumnMappings.Add("Website", "Website");
objbulk.ColumnMappings.Add("Location", "Location");
objbulk.ColumnMappings.Add("Targetted for", "TargettedFor");
con.Open();
objbulk.WriteToServer(Exceldt);
con.Close();
}
}
}
How to prevent duplicate data from Excel sheets when importing into SQL Server table?
Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};
I need to insert a row into a DataTable using a OleDbDataAdapter. However, my table has more than 100000 records and I don't want to load all the records.
My current code loads all the records into the DataTable
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Is there a way to insert data into my table without filling my datatable with all the rows other than adding "where 1 = 0" to my statement
EDIT
I need to use a DataAdapter to do this
Call FillSchema instead of Fill
As per request:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Yes, by using the DbCommand class to execute an INSERT.
Your code will probably look something like
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
var query = "INSERT INTO Nodes (nID, csNumber) " +
"VALUES (?, ?)";
var command = new OleDbCommand( query, connection);
command.Parameters.AddWithValue("#nID", nNodeID);
command.Parameters.AddWithValue("#csNumber", strNumber);
connection.Open();
command.ExecuteNonQuery();
}
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
try
oleconnStkNames = new OleDbConnection(strAccessConnectionString);
oleconnStkNames.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oleconnStkNames; //new OleDbConnection(strAccessConnectionString);
cmd.CommandText = "TheName of your InsertQuery "; // name of the query you want to run
cmd.CommandType = CommandType.StoredProcedure; // or System.Data.CommandType.Text if you are not using a Access StoredProc
OleDbDataReader rdr = cmd.ExecuteReader();
catch (Exception ex)
{
bla..bla..bla
}
//if you want to wrap it in a using() and add transactional processing use this example that I've written to fit what ever it is you are doing..
using (OleDbCommand olecmdStkNames = new OleDbCommand(strSQL, oleconnStkNames))
{
olecmdStkNames.CommandTimeout = 60;
oletransStockList = oleconnStkNames.BeginTransaction();
olecmdStkNames.Transaction = oletransStockList;
olecmdStkNames.CommandType = System.Data.CommandType.Text;
try
{
intRecordsAffected = olecmdStkNames.ExecuteNonQuery();
oletransStockList.Commit();
}
catch (OleDbException oledbExInsert_Update)
{
oletransStockList.Rollback();
Console.WriteLine(oledbExInsert_Update.Message);
}
((IDisposable)oletransStockList).Dispose();
}
my excel
|Name|Telephone|
|Color|Car|
|John|Jon|
i need "|John|Jon|" how to select OleDbCommand? third row start
My Csharp Not Work Code:
ExcelCommand.CommandText = #"SELECT * FROM " + SpreadSheetName + " Where RowNumber > 3";
Thank you...
This worked for me. You can change the SELECT statement as you wish (specific rows, multiple columns, ...) to get a single result or a set of rows returned.
string connectionString = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=test.xls;";
connectionString += "Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(connectionString);
DataSet ds = new DataSet("stuff");
OleDbDataAdapter adapter = new OleDbDataAdapter();
// adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$A1:A100];", con);
// adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$];", con);
adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$] where [A] = 'John';", con);
adapter.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
Console.WriteLine(dr[dc].ToString());
}
}
May be instead "RowNumber > 3" use "RowNumber = 3". "|John|Jon|" - third row.