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.
Related
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.
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 need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
public DataTable UserUpdateTempSettings(int install_id, int install_map_id, string Setting_value,string LogFile)
{
SqlConnection oConnection = new SqlConnection(sConnectionString);
DataSet oDataset = new DataSet();
DataTable oDatatable = new DataTable();
SqlDataAdapter MyDataAdapter = new SqlDataAdapter();
try
{
oConnection.Open();
cmd = new SqlCommand("SP_HOTDOC_PRINTTEMPLATE_PERMISSION", oConnection);
cmd.Parameters.Add(new SqlParameter ("#INSTALL_ID", install_id));
cmd.Parameters.Add(new SqlParameter ("#INSTALL_MAP_ID", install_map_id));
cmd.Parameters.Add(new SqlParameter("#SETTING_VALUE", Setting_value));
if (LogFile != "")
{
cmd.Parameters.Add(new SqlParameter("#LOGFILE",LogFile));
}
cmd.CommandType = CommandType.StoredProcedure;
MyDataAdapter.SelectCommand = cmd;
cmd.ExecuteNonQuery();
MyDataAdapter.Fill(oDataset);
oDatatable = oDataset.Tables[0];
return oDatatable;
}
catch (Exception ex)
{
Utils.ShowError(ex.Message);
return oDatatable;
}
finally
{
if ((oConnection.State != ConnectionState.Closed) || (oConnection.State != ConnectionState.Broken))
{
oConnection.Close();
}
oDataset = null;
oDatatable = null;
oConnection.Dispose();
oConnection = null;
}
}
I have used ExecuteNonQuery above. Normally it's not used with SqlDataAdapter. If I do not use it, I get an error.
Is it bad programming practice to use ExecuteNonQuery with SqlDataAdapter?
Hi deepti you don't have to call executeNonQuery because the fill method of the dataadapter is taking care for you. Here is a small sample:
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// 1
// Open connection
using (SqlConnection c = new SqlConnection(
Properties.Settings.Default.DataConnectionString))
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
// dataGridView1.DataSource = t; // <-- From your designer
}
}
}
}
I don't think it's a matter of bad practice, it just doesn't make sense to do it in this situation. The fill method is used to populate the results from a select command. ExecuteNonQuery() is normally used when you're not retrieving data, and will only return the number of results.
You can find more about the fill method here