I would really appreciate a help in this code. I have a DataSet with two tables; I need to create a relation based on two columns as primary key:
public DataSet GetAll()
{
string sql = $#"SELECT * FROM Journal ORDER BY JvNO, cYear;
SELECT * FROM JournalDetail ORDER BY JvNO, cYear";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("Journal_Batch", new DataColumn[] { ds.Tables[0].Columns["JvNO"], ds.Tables[0].Columns["cYear"] },
new DataColumn[] { ds.Tables[1].Columns["JvNO"], ds.Tables[1].Columns["cYear"] });
return ds;
}
}
Currently, I'm doing it like this and it's working but I need it with DataSet relation:
public DataSet GetJournalByID(int JVNO, int cYear)
{
string sql = $#"SELECT * FROM Journal WHERE JvNO = { JVNO } and cYear = { cYear };
SELECT * FROM JournalDetail WHERE JvNO = { JVNO } and cYear = { cYear };";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
I don't know what's wrong with first code, as it returns all matching JvNO or Year.
i want to use the first one to fill two grids as follow:
private void GetData()
{
DataSet currentDs = new DataSet();
grdJournalDetails.DataSource = null;
grdJournal.DataSource = null;
JournalConnector journalConnection = new JournalConnector();
currentDs = journalConnection.GetAll();
grdJournal.DataSource = currentDs.Tables[0];
grdJournalDetails.DataSource = currentDs.Tables[1];
}
then with each row selected from grdJournal to display grdJournalDetails with related data without calling each time the second snippet of code.
i used Dapper and i'm familiar with it, but with devexpress grid, it have to be a datatable to use the event gvJournal_FocusedRowChanged, otherwise datarow returns always null;
Thanks for any suggestion.
Related
The way this works, a drop down list has Price Groups in it and I need to get that Price Group and plug it into the stored procedure (_getVendorDetails) to get the Vendor ID. Then I need to put the Vendor ID into another stored procedure (DIST_get_POShortagesaAndExtra_VendorIDNotes) to get notes about the Vendor ID.
protected void LoadExtraVendorIDNotes()
{
if (ddlVendorPriceGroup.SelectedValue == "NA")
return;
DataSet ds = getVendorIDNotesPONotifications(ddlVendorPriceGroup.SelectedValue);
if (ds.Tables[0].Rows.Count > 0)
{
DataTable dt = ds.Tables[0];
lblShipmentScrutinyLow.Visible = Convert.ToBoolean(dt.Rows[0]["ShipmentScrutiny"].ToString());
lblContainsKitsLow.Visible = Convert.ToBoolean(dt.Rows[0]["ContainsKits"].ToString());
lblShippingIssuesLow.Visible = Convert.ToBoolean(dt.Rows[0]["ShippingIssues"].ToString());
lblMeetingNotesLow.Text = Convert.ToString(dt.Rows[0]["MeetingNotes"].ToString());
lblMeetingNotesLow.Visible = Convert.ToString(dt.Rows[0]["MeetingNotes"].ToString()).Length > 0;
lblShipmentNotesLow.Text = Convert.ToString(dt.Rows[0]["ShippingNotes"].ToString());
lblShipmentNotesLow.Visible = Convert.ToString(dt.Rows[0]["ShippingNotes"].ToString()).Length > 0;
}
}
protected DataSet getVendorIDNotes(string VENDORID)
{
DataSet ds = new DataSet();
using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["MeyerConnectionString"]))
{
using (SqlDataAdapter dadapter = new SqlDataAdapter())
{
dadapter.SelectCommand = new SqlCommand("DIST_get_POShortagesaAndExtra_VendorIDNotes", objConn);
dadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter vendorID = new SqlParameter("#VENDORID", VENDORID);
dadapter.SelectCommand.Parameters.Add(vendorID);
dadapter.Fill(ds);
}
}
return ds;
}
protected DataSet getVendorIDNotesPONotifications(string VENDORID)
{
DataSet ds = new DataSet();
using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["MeyerConnectionString"]))
{
using (SqlDataAdapter dadapter = new SqlDataAdapter())
{
dadapter.SelectCommand = new SqlCommand("_getVendorDetails", objConn);
dadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter vendorID = new SqlParameter("#pricegroup", VENDORID);
dadapter.SelectCommand.Parameters.Add(vendorID);
dadapter.Fill(ds);
}
}
return ds;
}
Going by your example code it seems you are on the right track just that you need to invoke the getVendorIDNotes method from within the getVendorIDNotesPONotifications method and pass the vendorID to it.
The dataset returned from getVendorIDNotes is further returned from the calling method i.e. getVendorIDNotesPONotifications and hence the logic in LoadExtraVendorIDNotes should work as expected.
public queue getQueueDataByID(int queueID)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
queue myQueue = new queue();
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.AppendLine("Select * from QueueTable where");
sqlCommand.AppendLine("id = #paraId");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
// sqlCommand.Parameters.AddWithValue("paraCustId", tbCustId.Text);
da = new SqlDataAdapter(sqlCommand.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("paraId", queueID);
// fill dataset
da.Fill(ds, "QueueTable");
//conn.Close();
int rec_cnt = ds.Tables["QueueTable"].Rows.Count;
DataRow row = ds.Tables["QueueTable"].Rows[rec_cnt-1 ];
myQueue.queueNo = row["QueueNo"].ToString();
myQueue.NRIC = row["NRIC"].ToString();
myQueue.ContactNo = row["ContactNo"].ToString();
}
catch (SqlException ex)
{
}
return myQueue;
}
This is my class,I am trying to retrieve the datas from the last row of the database to display in a web form, any idea how i can do that? My "id", primary key is set as autoincrement.
You can use Linq on the datatable to get the last row.
var queueDataTable = ds.Tables[0];
var lastDataRow = queueDataTable.AsEnumerable().Last();
If you need to itterate through all the rows in the datatable
foreach (var dataRow in queueDataTable.AsEnumerable())
{
}
thanks
im creating wfp application i want to retrieve table to datagridview
with multi value selected in listbox, getting all data that selected from listbox, so the main idea
is apply this query from sql to application
select * from Vwtb where firstname='' or firstaname='' or ..
i have tried with while loop and searched a lot but not worked this is my code please if its something strange for you im not professional :)
string[] orand = { "or"+listBox1.Text };
foreach (string sm in orand)
{
cn.Open();
string select = "select * from productvw where firstname='" + sm + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
}
any type of help will be so appreciated ....
You can convert your array to a string that can be used in IN operator.for achieving that, use this extension method
public static class StaticClass
{
public static string ConvertStringArrayToString(this string[] array)
{
StringBuilder builder = new StringBuilder();
for (int i=0;i<array.Length;i++)
{
builder.Append(array[i]);
if(i+1==array.Length)break;
builder.Append(',');
}
return builder.ToString();
}
}
Then in your code use it like this
string[] orand = { "or"+listBox1.Text };
var values=orand.ConvertStringArrayToString();
cn.Open();
string select =" SELECT * FROM productvw WHERE firstname IN "+"("+values+")"
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
You could use the IN operator.
string command = "SELECT * FROM productvw WHERE firstname IN (#names)";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
dataAdapter.Parameters.Add("#names", names);
The names would be a list of strings, List<string>, and would contain all the first names you want to use.
You can use the following syntax:
SELECT *
FROM productvw
WHERE firstname IN (value1,value2,...);
Start by creating a loop that generates the sql string With the values populated.
I would like to make one call (containing several SELECT statement) to the database and then databind the results to multiple components.
I'm using a DataSet and SqlDataAdapter to fill tables that are then bound to components.
Problem is the results of the first SELECT statement are put into both tables so I get a "'System.Data.DataRowView' does not contain a property..." error when I try to use the second lot of data on the second component.
Have I misunderstood how this is meant to work?
DataSet ds = new DataSet();
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);
StringBuilder topicDropDownListSQL = new StringBuilder();
topicDropDownListSQL.Append("SELECT topic.topic_ID, topic.topic_title FROM FPL2012_TOPIC as topic WHERE topic.topic_isEnabled = 1;");
topicDropDownListSQL.Append("SELECT explain.itemExplanationType_ID, explain.itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE as explain;");
SqlDataAdapter da = new SqlDataAdapter(topicDropDownListSQL.ToString(), connection);
ds.Tables.Add("Topics");
ds.Tables.Add("ExplainType");
ds.EnforceConstraints = false;
ds.Tables["Topics"].BeginLoadData();
da.Fill(ds.Tables[0]);
ds.Tables["Topics"].EndLoadData();
ds.Tables["ExplainType"].BeginLoadData();
da.Fill(ds.Tables[1]);
ds.Tables["ExplainType"].EndLoadData();
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataSource = ds.Tables["Topics"];
topicDropDownList.DataBind();
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataSource = ds.Tables["ExplainType"];
explanationTypeDropDownList.DataBind();
connection.Close();
You can use this acces the tables by there indexes not by there names
DataSet ds = new DataSet();
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);
String qry="SELECT topic_ID,topic_title FROM FPL2012_TOPIC WHERE topic_isEnabled = 1; SELECT itemExplanationType_ID, itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE ";
SqlDataAdapter da = new SqlDataAdapter(qry, connection);
da.Fill(ds)
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataSource = ds.Tables[0];
topicDropDownList.DataBind();
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataSource = ds.Tables[1];
explanationTypeDropDownList.DataBind();
connection.Close();
OK, I tried using a datareader next, didn't expect it to work but it does! I can make multiple select statements and then fill multiple componenets. I'm not marking this as an answer as I still think it would be useful to know how to do it using the dataset.
The new code that worked for me (in case it is useful):
string connectionString = WebConfigurationManager.ConnectionStrings["myString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
StringBuilder sql = new StringBuilder();
sql.Append("SELECT topic.topic_ID, topic.topic_title FROM FPL2012_TOPIC as topic WHERE topic.topic_isEnabled = 1;");
sql.Append("SELECT explain.itemExplanationType_ID, explain.itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE as explain;");
SqlCommand command = new SqlCommand(sql.ToString(), connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
topicDropDownList.DataSource = reader;
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataBind();
reader.NextResult();
explanationTypeDropDownList.DataSource = reader;
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataBind();
reader.Close();
connection.Close();
This is my Method:
Datatable data2 = new Datatable();
int result = 0;
using (SqlConnection conn = new SqlConnection(connStr))
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT * from TableA";
SqlDataAdapter da = new SqlDataAdapter(cmd);
result = da.Fill(data2);
if (result > 0)
{
this.dgBatch.DataSource = data2;
}
else
{
MessageBox.Show("No Records!");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
If I call this Method consecutively it always Add Rows from the first Query.
Ex:
Table Data: 5
First Call: 5
Second Call: 10. It duplicates all Records from first Call.
Thanks in Regards
That is because you are reusing data2. You should create a new instance for data2 before the following line:
result = da.Fill(data2);
Assuming data2 is a datatable
result = da.Fill(data2); will always merge the results because you are using same instance of datatable.
if you want to get every time a fresh copy than create a new instance of datatable and than fill this instance with data.
so the line before result = da.Fill(data2); add following line.
data2 = new Datatable();