DataGridView Index out of range - c#

I am new to C # and have a small problem with DataGridView. I have two codes selected in my database to fill this grid with different columns. I want the user to see only the columns I select, when I start, this works perfectly, but when I try to search the other columns, I get this message: "System.ArgumentOutOfRangeException: 'index was out of range. It must be non-negative and less than the size of the collection 'Arg_ParamName_Name' "
i've tryied to clear the index columns or restart the dataviewgrid, but no success! need help!
private void ConfiguraDataGridView(int i)
{
switch (i)
{
case 1:
//setando nome do cabeçalho
dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
dgAlmoxarifado.Columns[1].HeaderText = "Cor";
dgAlmoxarifado.Columns[2].HeaderText = "Marca";
dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
dgAlmoxarifado.Columns[7].HeaderText = "Quantidade Recomendada";
dgAlmoxarifado.Columns[8].HeaderText = "Data de Cadastro";
dgAlmoxarifado.Columns[9].HeaderText = "Cadastro";
break;
case 2:
//setando nome do cabeçalho
dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
dgAlmoxarifado.Columns[1].HeaderText = "Cor";
dgAlmoxarifado.Columns[2].HeaderText = "Marca";
dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
dgAlmoxarifado.Columns[7].HeaderText = "Requisição";
dgAlmoxarifado.Columns[8].HeaderText = "Data de Requisição";
dgAlmoxarifado.Columns[9].HeaderText = "Quantidade Requisitada";
dgAlmoxarifado.Columns[10].HeaderText = "Reposição";
dgAlmoxarifado.Columns[11].HeaderText = "Data de Reposição";
dgAlmoxarifado.Columns[12].HeaderText = "Quantidade Repositada";
dgAlmoxarifado.Columns[13].HeaderText = "Observação";
break;
}
}
private void ResetDataGridView()
{
// dgAlmoxarifado.CancelEdit();
// dgAlmoxarifado.Dispose();
dgAlmoxarifado.Columns.Clear();
dgAlmoxarifado.Refresh();
dgAlmoxarifado.DataSource = null;
}
EDIT: The entire code about this event.
Load Object:
private void IEstoque_Load(object sender, EventArgs e)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
ConfiguraDataGridView(1);
}
Pass to BLL:
public DataTable CarregarGrid(int opcao, string nomeBusca)
{
return cb.CarregarGrid(opcao, nomeBusca);
}
Pass to DAL:
public DataTable CarregarGrid(int opcao, string nomeBusca)
{
DataTable dt = new DataTable();
string comando = string.Empty;
switch (opcao)
{
case 1:
comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, i.quantidadeRecomendada, i.cadastradoNoDia, u.nomeUsuario from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like #nome ";
break;
case 2:
comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, m.requisicao, m.dataRequisicao, m.quantidadeRequisitada, m.observacaoRequisicao,m.reposicao, m.dataReposicao, m.quantidadeReposicao, m.observacaoReposicao from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like #nome ";
break;
}
MySqlCommand cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("#nome", "%"+ nomeBusca +"%");
try
{
Conectar();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (MySqlException ex)
{
string erro = ex.Message;
return dt;
}
finally
{
Desconectar();
}
}
Then i have this button search:
private void btnSearch_Click(object sender, EventArgs e)
{
if (rdItem.Checked == true)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
ConfiguraDataGridView(1);
}
else if (rdMovimentacao.Checked == true)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(2, txtSearch.Text);
ConfiguraDataGridView(2);
}
}
When i press that button occurs the error!

Don't clear the columns, just set the DataSource to null and then set it to the corresponding DataSource.

It worked, thanks to everyone who helped, I had a problem with my select (
an error in the field name) and after following the tip from #Jannick Breunis about cleaning only the datasource and the tip from #Nbk about directly checking the filling of the Data Table was solved.

Related

How to filter one dropdownlist based on another selection

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;
}
}

Date-picker using select statement oracle

I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences

Row to not visible if null

I am using windows form to build an application using datagridview. Every data grid contains an empty row at the top and I suspect that it is the way that I am populating them but as I am coming to the end, I am reluctant to change any of my code as I am a beginner.
Is there a simple way to check if a row if empty, then set that to not visible?
The code that I am using:
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
customersDataGridView.Rows.Add();
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
rowadd.Cells[1].Value = reader["Forename"].ToString();
rowadd.Cells[2].Value = reader["Surname"].ToString();
rowadd.Cells[3].Value = reader["Address"].ToString();
rowadd.Cells[4].Value = reader["Town"].ToString();
rowadd.Cells[5].Value = reader["Postcode"].ToString();
rowadd.Cells[6].Value = reader["Date_Of_Birth"].ToString();
rowadd.Cells[7].Value = reader["Phone_Number"].ToString();
rowadd.Cells[8].Value = reader["Email"].ToString();
rowadd.Cells[9].Value = reader["Current_Rental"].ToString();
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
reader.Close();
connect.Close();
}
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
}
You could use the IsNullOrWhiteSpace. But before that, you have to check your sql statement, why you have empty rows result.
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
if (!string.IsNullOrWhiteSpace(reader["Customer_ID"].ToString()))
{
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
//Others Stuff
//...
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
}

Populate dropdownlist with datareader from database

Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific dropdownlist that user selected before. Im using linqdatasource to show all the dropdownlist value.
public partial class Update : System.Web.UI.Page
{
string cs = Global.CS;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // only during initial load
{
string id = Request.QueryString["Item_ID"] ?? "";
string sql = "Select * FROM MenuItem WHERE Item_ID = #id";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Id", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
{
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
//foreach (var checking in db.Sets)
//{
// string setID = checking.Set_ID.ToString();
// if (setID == (string)dr["Item_ID"])
// {
// ddlAlacarte.DataSourceID = "ldsAlacarte";
// **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
// ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
// }
//}
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
}
}
else
{
Response.Redirect("MenuAdmin.aspx");
}
DataBind();
dr.Close();
con.Close();
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
{
ddlAlacarte.Enabled = true;
ddlBeverage.Enabled = true;
ddlSide.Enabled = true;
DataBind();
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
}
}
}
You need to add items in Dropdownlist while reading values.
Add the following code while you are reading values by using SqlDataReader.
while(dr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = dr["Category"].ToString();
listItem.Value = dr["Category"].ToString();
categoryDropDownList.Items.Add(listItem);
}
I would use something like this
dropDownList.Items.Add(
new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);
and iterate through, populating the dropdown list. Is that what you want ?

Trouble updating my datagrid in WPF

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

Categories

Resources