I have been making a UI panel and have dynamic data for input to the interface.
For this I want a filter an SQL query based on user selected valus of several SQL querys.
For a prototype:
I generated the panel and got the data to appear no problems, but since I do not know how many filters I will have until I look at the first query I made the checkboxes and dropdowns on the filter dynamically.
The problem I have is I cannot access the user selected values in the dropdowns or the checkboxes.
I assigned unique ID's to each element so the fastest solution would be the c# equivalent of getElementByID?
I will post some of the code below:
protected string SQConnWhere(string TableName = "Nonya", string FieldName = "Error!!!", int i=0)
{
string ConnectionString = "real string removed";
cmdText = #"SELECT DISTINCT " + FieldName + " FROM tablenamechangedfromrealonetoprotectthe innocent";
Label myLabel = new Label();
Label myLabelA = new Label();
CheckBox myCheckBox = new CheckBox();
DropDownList myList = new DropDownList();
myList.ID = "myList" + i;
myCheckBox.ID = "myCheckBox" + i;
myLabel.ID = "myLabel" + i;
myLabelA.ID = "myLabelA" + i;
myLabel.Text = FieldName;
PlaceHolder1.Controls.Add(myLabel);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(myList);
myCheckBox.Text = "Use This Field in Filter?";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
myList.DataSource = ds2;
myList.DataTextField = FieldName;
myList.DataBind();
ViewState["Data"] = ds2;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
PlaceHolder1.Controls.Add(myCheckBox);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
//May not need this?
//filterList.Add(FieldName);
myLabelA.Text = cmdText;
PlaceHolder1.Controls.Add(myLabelA);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
//myCheckBox.CheckedChanged += new EventHandler(UpdatemyCheckBox);
//pnlCheckList.Controls.Add(myCheckBox);
// register the control to cause asynchronous postbacks
//ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(myCheckBox);
//Label4.Text = FieldName;
return cmdText;
}
P.S. This is my first post despite browsing the website for a long time, thanks for all the help thus far!!!
I solved it using
ManualSQConnWhere(DropDownList1, myTable, "Run_ID", CheckBox1);
ManualSQConnWhere(DropDownList2, myTable, "Job_Status", CheckBox2);
ManualSQConnWhere(DropDownList3, myTable, "Job_Plan", CheckBox3);
protected string ManualSQConnWhere(DropDownList myList, string TableNameWeb2, string FieldName, CheckBox myCheckBox)
{
string ConnectionString = "Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True";
cmdText = #"SELECT DISTINCT " + FieldName + " FROM " + TableNameWeb2;
DataSet dbWeb2 = new DataSet();
myList.AutoPostBack = false;
//myList.ViewStateMode = ViewStateMode.Enabled;
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn);
adapter.Fill(dbWeb2);
ViewState["Data"] = dbWeb2;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
myList.AppendDataBoundItems = true;
myList.DataSource = dbWeb2;
myList.DataTextField = FieldName;
myList.Items.Add(new ListItem("<None Selected>", string.Empty));
if (dbWeb2.Tables.Count > 0)
{
myList.DataBind();
}
else
{
Label1.Text = "Error on the SQL Query" + cmdText;
return cmdText;
}
myCheckBox.Text = FieldName;
return cmdText;
}
This code propogated the dropdowns and I simply entered the tags for them
Related
I am trying to perform CRUD operation on winform
This is for ASP.NET winform in which whenever I try to insert, update or delete the data to or from the database first of all rows and inside content gets duplicated
https://imgur.com/a/d5jgv6H
however, upon restarting the application data shows up correctly
private void button2_Click(object sender, EventArgs e)
{
//insert
try
{
con.Open();
//.text property gets/Sets text associated with this control
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String number = textBox3.Text.ToString();
long pnumber = Int64.Parse(number);
String sem = textBox4.Text.ToString();
long semester = Int64.Parse(sem);
string branch = comboBox1.SelectedItem.ToString();
String query = "insert into student values('" + name + "','" + address + "'," + pnumber + "," + semester + ",'" + branch + "')";
SqlCommand sqlcom = new SqlCommand(query, con);
int i = sqlcom.ExecuteNonQuery();
if (i >= 1)
{
MessageBox.Show("Student has been Registered: " + name);
}
else
{
MessageBox.Show("Registration Failed ! ");
}
//clearing data
button1_Click(sender, e);
show();
con.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error is : " + exp.ToString());
}
}
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
//DataRow represents row of data in DataTable
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
The query works fine but rows still get duplicated. What's the problem?
I can't find any bug, so I assume I am doing something incorrectly.
Your show method adds rows to the grid, but it never removes the rows which are already in the grid.
Normally one would use data binding to populate a DataGridView or other data-bound controls. I'm going to assume you have reasons for just adding rows directly (perhaps it's simpler for your needs) and not change that. Given that structure, probably the easiest thing to do is just to clear the grid before adding the new rows:
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
dataGridView1.Rows.Clear(); // <--- here
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
That way any time you are about to populate the grid with new data, you first clear the existing data from it.
I have a problem in updating my data.
I have Home.aspx.cs and a class HomeClass.cs. I have a gridview in which I want to do my updating but it doesn't work.
It won't return the successful message and I also checked my SQL Server database but there's no changes.
This is my Home.aspx.cs:
protected void DataGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = DataGridView.Rows[e.RowIndex];
// get old data
HiddenField hidedescription = row.FindControl("hiddendescription") as HiddenField;
HiddenField hidepkgcode = row.FindControl("hiddenpkgcode") as HiddenField;
HiddenField hideoprcode = row.FindControl("hiddenoprcode") as HiddenField;
// get new data
DropDownList Ed_description = DataGridView.Rows[e.RowIndex].FindControl("Editdescription") as DropDownList;
TextBox Ed_pkgcode = DataGridView.Rows[e.RowIndex].FindControl("Editpkgcode") as TextBox;
TextBox Ed_oprcode = DataGridView.Rows[e.RowIndex].FindControl("Editoprcode") as TextBox;
string Message = obj.Update_Data(Ed_description.SelectedItem,
Ed_pkgcode,
Ed_oprcode,
hidedescription.Value,
hidepkgcode.Value,
hideoprcode.Value);
Fill_Grid();
Literal1.Text = Message;
}
catch (Exception ex)
{
}
}
void Fill_Grid()
{
try
{
DataGridView.DataSource = obj.Get_Data();
DataGridView.DataBind();
}
catch (Exception ex)
{
}
}
And this is my HomeClass.cs class:
static string Connect = WebConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(Connect);
SqlCommand cmd;
SqlDataAdapter adap;
DataTable dt;
public string Update_Data(ListItem listItem,
TextBox Ed_pkgcode,
TextBox Ed_oprcode,
string hidedescription,
string hidepkgcode,
string hideoprcode)
{
// update data
string getnewType = listItem.Text;
if (getnewType == "Data 1")
{
getnewType = "Y";
}
if (getnewType == "Data 2")
{
getnewType = "N";
}
// old data
if (hidedescription == "Data 1") { hidedescription = "Y"; }
if (hidedescription == "Data 2") { hidedescription = "N"; }
con.Open();
cmd = new SqlCommand("Update PAORStdTime set type='" + getnewType +
"', pkgcode='" + Ed_pkgcode.Text +
"', oprcode='" + Ed_oprcode.Text +
"' where type= '" + hidedescription +
"' and pkgcode ='" + hidepkgcode +
"' and oprcode ='" + hideoprcode + "'" , con);
cmd.ExecuteNonQuery();
con.Close();
return "Updated successfully";
}
where type = hidedescription
and pkgcode = hidepkgcode
and pkgcode = hideoprcode
There is no way that pkgcode will be equal to both hidepkgcode and hideoprcode. I believe the code below is what you want.
where type = hidedescription
and pkgcode = hidepkgcode
and oprcode = hideoprcode
I have the following code which populates the Topic dropdownlist and saves it to a cached table:
bookingData2 = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query2 = #"Select * from [DB].dbo.[top]";// columng #1 = Specialty and column #2 = Topic
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query2, conn);
SqlDataAdapter da = new SqlDataAdapter(query2, conn);
da.Fill(bookingData2);
HttpContext.Current.Cache["cachedtable2"] = bookingData2;
bookingData2.DefaultView.Sort = "Topic ASC";
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
I have the following code which populates the Specialty dropdownlist and saves it to another cached table:
bookingData = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query = #"select * from [DB].dbo.[SP]";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(bookingData);
bookingData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = bookingData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
Specialty.Items.Remove("All Specialties");
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
How can I code the Specialty dropdownlist index change to do the following and save it to a cache table for quick access:
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
--> Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
}
Save bookingData2 table in ViewState or Session (I won't recommend to use session though) if it's not too heavy. Otherwise, its better you cache it or query the database again to repopulate it.
Let's assume you save bookingData2 in ViewState as follows in Page_Load
ViewState["bookingData2"] = bookingData2; // This should be before the following line
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic");
Then in your SelectedIndexChanged event do something like this
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
// Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
DataTable bookingData2 = (DataTable)ViewState["bookingData2"];
Topic.DataSource = bookingData2.Where(i => i.Specialty == "All Specialties" || i.Specialty == Specialty.SelectedValue).DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
}
Update - With Cached object
Do following in Specialty_SelectedIndexChanged event instead of where we used ViewState before.
if (HttpRuntime.Current.Cache["cachedtable2"] != null)
{
DataTable bookingData2 = HttpRuntime.Current.Cache["cachedtable2"] as DataTable;
// Rest of the code
}
I haven't tried this code. Let me know if you find any issues.
This is what solved it for me:
protected void Topic_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Topic.SelectedIndex == 0)
{
string query = #"Specialty LIKE '%%'";
DataTable cacheTable = HttpContext.Current.Cache["cachedtable"] as DataTable;
DataTable filteredData = cacheTable.Select(query).CopyToDataTable<DataRow>();
filteredData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = filteredData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
else
{
string qpopulate = #"[Topic] = '" + Topic.SelectedItem.Value + "' or [Topic] = 'All Topics'"; //#"Select * from [DB].dbo.[table2] where [Specialty] = '" + Specialty.SelectedItem.Value + "' or [Specialty] = 'All Specialties'";
DataTable cTable = HttpContext.Current.Cache["cachedtable2"] as DataTable;
DataTable fData = cTable.Select(qpopulate).CopyToDataTable<DataRow>();
if (fData.Rows.Count > 0)
{
fData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = fData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
}
}
catch (Exception ce)
{
string error = ce.Message;
}
}
I am able to retain the DropDownListCheckbox multi-selected items text inside a label with a button click. I need to search from the database based on the DropDownListCheckBox multi selected items and its related data from a SQL-Server database.
How to achieve the search option using a button click by passing the input from DDL_CB list items or label text to parameterized SQL query?
My requirement: the search feature must display the data in JQgrid based on the text contained in the Label or DDL_CheckBox multi-selected items.
My C# code:
static string value1;
static string value2;
static string value3;
protected void createmaincontrols()
{
//Create a Dynamic Panel
DynamicPanel = new Panel();
DynamicPanel.ID = "DynamicPanel";
DynamicPanel.Width = 1600;
//Create Main Table
var dynamic_filter_table = new WebForms.Table();
dynamic_filter_table.ID = "dynamic_filter_table_id";
TableRow campaign_table_row = new TableRow();
campaign_table_row.ID = "country_table_row";
TableRow campaign_label_row = new TableRow();
campaign_label_row.ID = "country_label_row";
TableCell campaignnamecell = new TableCell();
campaignnamecell.ID = "countrynamecell";
TableCell btncell = new TableCell();
btncell.ID = "btncell";
TableCell labelcell = new TableCell();
labelcell.ID = "labelcell";
//Create Campaigns DDL
DropDownCheckBoxes DDL_checkbox = new DropDownCheckBoxes();
DDL_checkbox.ID = "MainDDL_Countries";
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.ForeColor = System.Drawing.Color.MidnightBlue;
DDL_checkbox.Font.Size = FontUnit.Point(8);
DDL_checkbox.Font.Bold = true;
DDL_checkbox.Font.Name = "Arial";
DDL_checkbox.AddJQueryReference = true;
DDL_checkbox.UseButtons = true;
DDL_checkbox.UseSelectAllNode = true;
DDL_checkbox.Style.SelectBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxHeight = 130;
DDL_checkbox.Texts.SelectBoxCaption = "Select Countries";
DDL_checkbox.Items.Add(new ListItem("SINGAPORE"));
DDL_checkbox.Items.Add(new ListItem("UNITED KINGDOM"));
DDL_checkbox.Items.Add(new ListItem("MALAYSIA"));
DDL_checkbox.Items.Add(new ListItem("INDIA"));
DDL_checkbox.Items.Add(new ListItem("FRANCE"));
DDL_checkbox.Items.Add(new ListItem("GERMANY"));
DDL_checkbox.Items.Add(new ListItem("NORWAY"));
DDL_checkbox.DataTextField = "Country Name";
DDL_checkbox.DataBind();
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.EnableViewState = false;
Button submitbutton = new Button();
submitbutton.ID = "mybutton";
submitbutton.Text = "SubmitSelectedCountries";
submitbutton.Click += new EventHandler(Buttonnew_Click);
submitbutton.Font.Name = "Arial";
submitbutton.Font.Bold = true;
submitbutton.Font.Size = FontUnit.Point(8);
submitbutton.ForeColor = System.Drawing.Color.MidnightBlue;
submitbutton.BackColor = System.Drawing.Color.LightGray;
submitbutton.UseSubmitBehavior = false;
Label lblCampaignName = new Label();
lblCampaignName.ID = "Countries";
lblCampaignName.Font.Bold = true;
lblCampaignName.Font.Size = FontUnit.Point(8);
lblCampaignName.ForeColor = System.Drawing.Color.MidnightBlue;
lblCampaignName.BackColor = System.Drawing.Color.LightGray;
campaignnamecell.Controls.Add(DDL_checkbox);
campaignnamecell.Controls.Add(submitbutton);
campaignnamecell.Controls.Add(lblcountryname);
campaign_table_row.Controls.Add(countrycell);
dynamic_filter_table.Controls.Add(country_table_row);
DynamicPanel.Controls.Add(dynamic_filter_table);
SelectPanel.Controls.Add(DynamicPanel);
}
C# code to retrieve the dropdown checked items in a label using a button click
protected void Buttonnew_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
DropDownCheckBoxes DDL_checkbox = maintable.FindControl("MainDDL_Contries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Country") as Label;
List<String> Country_List = new List<string>();
foreach (System.Web.UI.WebControls.ListItem item in DDL_checkbox.Items)
{
if (item.Selected)
{
Country_List.Add(item.Text);
}
lblcountryname .Text = String.Join(",", Country_List.ToArray());
}
}
How to search the country details based on a parameterized SQL query input from label or dropdowncheckbox selected items?
protected void Button4_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
int rc = maintable.Rows.Count;
if (rc == 2)
{
//Three country selected in DDL_checkbox
DropDownCheckBoxes d4 = maintable.FindControl("MainDDL_Countries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Countries") as Label;
var countryname= test.ToString().Split(new[] { ',', '\n' }).ToArray();
if(countryname.Count() >=1 && countryname.Count() <=3)
{
value1 = countryname.ElementAt(0).ToString();
value2 = countryname.ElementAt(1).ToString();
value3 = countryname.ElementAt(2).ToString();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT C.Country_Name,C.Address FROM COUNTRYTABLE as C WHERE C.Country_Name in(#t4,#t5,#t6)";
cmd.Parameters.Add("#t4", SqlDbType.VarChar).Value = value1;
cmd.Parameters.Add("#t5", SqlDbType.VarChar).Value = value2;
cmd.Parameters.Add("#t6", SqlDbType.VarChar).Value = value3;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sql = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
sql.Fill(data);
con.Close();
Session["DataforSearch_DDL"] = data.Tables[0];
}
}
This is admittedly a partial answer. It will get you started.
When you submit a form with multi-selected items, the selected items are passed as comma separated values. Something like this:
value1,value2,etc
You want your query to have a where clause like this:
where someTextfield in ('value1','value2','etc')
or without the quotes for numeric fields. However, you wisely said that you wanted to use parameters.
Here endeth the partial answer.
long-long time ago, I used to do it this way:
for (int i = 0; i < param.Length; i++)
if (param[i] != "" && param[i] != null)
s_comm.Parameters.AddWithValue(tParam + i.ToString(), param[i]);
where:
private string tParam = "#Param";
string[] paramName // Name of the parameters
string[] param // Values for those parameters.
and I was building a statement like this:
string where = "";
if (paramName != null)
for (int i = 0; i < paramName.Length; i++)
if (paramName[i] != "" && paramName[i] != null)
if (i == 0)
where = " WHERE " + paramName[i] + " = " + tParam + i.ToString();
else
where += ", " + paramName[i] + " = " + tParam + i.ToString();
else throw new Exception(noColumnName + " at position #:" + i.ToString());
else where = "";
if (table != "") return "SELECT * FROM " + table + where;
I am sure there are more elegant solutions, but this is a start, right?
As the title indicates, I'm having trouble updating a datagrid in WPF. Basically what I'm trying to accomplish is a datagrid, that is connected to a SQL Server database, that updates automatically once a user enters information into a few textboxes and clicks a submit button. You'll notice that I have a command that joins two tables. The data from the Quote_Data table will be inserted by a different user at a later time. For now my only concern is getting the information from the textboxes and into the General_Info table, and from there into my datagrid. The code, which I'll include below compiles fine, but when I hit the submit button, nothing happens. This is the first application I've ever built working with a SQL Database so many of these concepts are new to me, which is why you'll probably look at my code and wonder what is he thinking.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public DataSet mds; // main data set (mds)
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
try
{
string connectionString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//Merging tables General_Info and Quote_Data
SqlCommand cmd = new SqlCommand("SELECT General_Info.Quote_ID, General_Info.Open_Quote, General_Info.Customer_Name,"
+ "General_Info.OEM_Name, General_Info.Qty, General_Info.Quote_Num, General_Info.Fab_Drawing_Num, "
+ "General_Info.Rfq_Num, General_Info.Rev_Num, Quote_Data.MOA, Quote_Data.MOQ, "
+ "Quote_Data.Markup, Quote_Data.FOB, Quote_Data.Shipping_Method, Quote_Data.Freight, "
+ "Quote_Data.Vendor_Price, Unit_Price, Quote_Data.Difference, Quote_Data.Vendor_NRE_ET, "
+ "Quote_Data.NRE, Quote_Data.ET, Quote_Data.STI_NET, Quote_Data.Mfg_Time, Quote_Data.Delivery_Time, "
+ "Quote_Data.Mfg_Name, Quote_Data.Mfg_Location "
+ "FROM General_Info INNER JOIN dbo.Quote_Data ON General_Info.Quote_ID = Quote_Data.Quote_ID",
connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
MainGrid.ItemsSource = dt.DefaultView;
mds = new DataSet();
da.Fill(mds, "General_Info");
MainGrid.DataContext = mds.Tables["General_Info"];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// renaming column names from the database so they are easier to read in the datagrid
MainGrid.Columns[0].Header = "#";
MainGrid.Columns[1].Header = "Date";
MainGrid.Columns[2].Header = "Customer";
MainGrid.Columns[3].Header = "OEM";
MainGrid.Columns[4].Header = "Qty";
MainGrid.Columns[5].Header = "Quote Number";
MainGrid.Columns[6].Header = "Fab Drawing Num";
MainGrid.Columns[7].Header = "RFQ Number";
MainGrid.Columns[8].Header = "Rev Number";
MainGrid.Columns[9].Header = "MOA";
MainGrid.Columns[10].Header = "MOQ";
MainGrid.Columns[11].Header = "Markup";
MainGrid.Columns[12].Header = "FOB";
MainGrid.Columns[13].Header = "Shipping";
MainGrid.Columns[14].Header = "Freight";
MainGrid.Columns[15].Header = "Vendor Price";
MainGrid.Columns[16].Header = "Unit Price";
MainGrid.Columns[17].Header = "Difference";
MainGrid.Columns[18].Header = "Vendor NRE/ET";
MainGrid.Columns[19].Header = "NRE";
MainGrid.Columns[20].Header = "ET";
MainGrid.Columns[21].Header = "STINET";
MainGrid.Columns[22].Header = "Mfg. Time";
MainGrid.Columns[23].Header = "Delivery Time";
MainGrid.Columns[24].Header = "Manufacturer";
MainGrid.Columns[25].Header = "Mfg. Location";
}
private void submitQuotebtn_Click(object sender, RoutedEventArgs e)
{
CustomerData newQuote = new CustomerData();
int quantity;
quantity = Convert.ToInt32(quantityTxt.Text);
string theDate = System.DateTime.Today.Date.ToString("d");
newQuote.OpenQuote = theDate;
newQuote.CustomerName = customerNameTxt.Text;
newQuote.OEMName = oemNameTxt.Text;
newQuote.Qty = quantity;
newQuote.QuoteNumber = quoteNumberTxt.Text;
newQuote.FdNumber = fabDrawingNumberTxt.Text;
newQuote.RfqNumber = rfqNumberTxt.Text;
newQuote.RevNumber = revNumberTxt.Text;
try
{
string insertConString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection insertConnection = new SqlConnection(insertConString))
{
insertConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(Sqtm.Properties.Settings.Default.SqtmDbConnectionString, insertConnection);
SqlCommand updateCmd = new SqlCommand("UPDATE General_Info " + "Quote_ID = #Quote_ID, "
+ "Open_Quote = #Open_Quote, " + "OEM_Name = #OEM_Name, " + "Qty = #Qty, "
+ "Quote_Num = #Quote_Num, " + "Fab_Drawing_Num = #Fab_Drawing_Num, "
+ "Rfq_Num = #Rfq_Num, " + "Rev_Num = #Rev_Num "
+ "WHERE Quote_ID = #Quote_ID");
updateCmd.Connection = insertConnection;
System.Data.SqlClient.SqlParameterCollection param = updateCmd.Parameters;
//
// Add new SqlParameters to the command.
//
param.AddWithValue("Open_Quote", newQuote.OpenQuote);
param.AddWithValue("Customer_Name", newQuote.CustomerName);
param.AddWithValue("OEM_Name", newQuote.OEMName);
param.AddWithValue("Qty", newQuote.Qty);
param.AddWithValue("Quote_Num", newQuote.QuoteNumber);
param.AddWithValue("Fab_Drawing_Num", newQuote.FdNumber);
param.AddWithValue("Rfq_Num", newQuote.RfqNumber);
param.AddWithValue("Rev_Num", newQuote.RevNumber);
adapter.UpdateCommand = updateCmd;
adapter.Update(mds.Tables[0]);
mds.AcceptChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance to anyone who can help, I really appreciate it,
Andrew
You are not setting the Quote_ID parameter. So your update it likely running WHERE Quote_ID = null so nothing updates.
using LINQ I was able to resolve the issue. Here's the code:
var sqtmDC = new SqtmLinqDataContext();
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
//join quoteData in sqtmDataContext.GetTable<Quote_Data>() on generalInfo.Quote_ID equals quoteData.Quote_ID
select generalInfo;
myGrid.ItemsSource = mainTable;
}
private void submitBtn_Click(object sender, RoutedEventArgs e)
{
var sqtmDC = new SqtmLinqDataContext();
// string theDate = System.DateTime.Today.Date.ToString("d");
int quantity = Convert.ToInt32(quantityTxt.Text);
General_Info insert = new General_Info();
insert.Open_Quote = DateTime.UtcNow;
insert.Customer_Name = customerNameTxt.Text;
insert.OEM_Name = oemNameTxt.Text;
insert.Qty = quantity;
insert.Quote_Num = quoteNumberTxt.Text;
insert.Fab_Drawing_Num = fabDrawingNumTxt.Text;
insert.Rfq_Num = rfqNumberTxt.Text;
insert.Rev_Num = revNumberTxt.Text;
sqtmDC.General_Infos.InsertOnSubmit(insert);
sqtmDC.SubmitChanges();
int quoteID = insert.Quote_ID;
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
select generalInfo;
myGrid.ItemsSource = mainTable;
Are you trying to update an existing row or insert a new row?
Cause if you need to insert then the proper command is insert (not update).
To get the Identity value of the inserted row you use Scope_Identity().
And you can only insert into one table at a time.
Scope_Identity() is NOT a param
Do not try and use it as a param
See example below
INSERT INTO Sales.Customer ([TerritoryID],[PersonID]) VALUES (8,NULL);
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
There are lots of examples on MSDN.Microsoft.com