Import ForeignKey values by ComboBox - c#

I'm trying to import a ForeignKey values using ComboBox, but the ComboBox loads string values and the ForeignKey type is int,I tried to convert ToString(),then I got error:
"The left hand side of an assignment must be a variable property or indexer"
ShippingDocumentDataClassesDataContext dc = new ShippingDocumentDataClassesDataContext();
t_tracking newInvoice = new t_tracking();
newInvoice.SupplierId.ToString() = comboBox1.Text;
dc.t_trackings.InsertOnSubmit(newInvoice);
dc.SubmitChanges();
Any help would be appreciated.

This line is wrong:
newInvoice.SupplierId.ToString() = comboBox1.Text;
you are trying to assign value to method call.
Instead this line should be:
newInvoice.SupplierId = Int32.Parse(comboBox1.Text);
or safer way:
int id = 0;
if (Int32.TryParse(comboBox1.Text, out id))
{
//we get valid integer from combobox
newInvoice.SupplierId = id;
dc.t_trackings.InsertOnSubmit(newInvoice);
dc.SubmitChanges();
}
else
{
//wrong value handling code goes here
}

Related

DataGridViewComboBoxCell Value not being set properly

I've been trying to set the value of an individual DataGridViewComboBoxCell for the last 4 hours and I've been getting nowhere. The most common solution I've seen was to set the .Value member of the DataGridViewComboBoxCell to one of the Items, which I tried and it complained the value was not valid.
DataTable documentTypes = _codedValues.GetCodedValues(Database.DOCUMENT_TYPE_TABLE); documentTypes.Columns[Database.PROFESSION_ID_COLUMN].AllowDBNull = true;
documentTypes.Columns[Database.CODE].AllowDBNull = true;
this.cbxDocumentType.DisplayMember = Database.VALUE;
this.cbxDocumentType.ValueMember = Database.CODE;
this.cbxDocumentType.DataSource = documentTypes.DefaultView;
int rowId = this.dgvDocumentList.Rows.Add(doc.actualName, doc.fileName);
DataGridViewComboBoxCell obj = (DataGridViewComboBoxCell)this.dgvDocumentList.Rows[rowId].Cells[2];
obj.Value = obj.Items[0];
After the message box comes up that tells me DataGridViewComboBoxCell view is not valid, I see the .ToString output of the object being set, which is System.Data.DataRowValue.
Depending what your datasource contains you must use the correct casts to access the correct fields.
Try this:
DataGridViewComboBoxCell cell =
(DataGridViewComboBoxCell)this.dgvDocumentList.Rows[rowId].Cells[2];
cell.Value = ((DataRowView)cell.Items[0]).Row.ItemArray[0];
This assumes that the Items are DataRowViews and that the ValueMember is in the first field.
You can test the type by writing an intermediate step:
var item = cell.Items[0];
And use the debugger to look into the resulting type..

Check if DataGridViewComboBox is empty

I have a datagridview with a combobox column that is bound to an enum as follows:
var D = (DataGridViewComboBoxColumn)dgvInputs.Columns[2];
D.ValueType = typeof(MyType);
D.ValueMember = "Value";
D.DisplayMember = "Display";
D.DataSource = new MyType[] {
MyType.Rev,
MyType.Model,
MyType.User,
MyType.Status
}.Select(x => new { Display = x.ToString(), Value = (int)x }).ToList();
The datagridview is then bound to a DataTable named ParameterTable:
BindingSource ParamSource = new BindingSource();
ParamSource.DataSource = DataEntry.ParameterTable;
dgvInputs.AutoGenerateColumns = false;
dgvInputs.DataSource = ParamSource;
dgvInputs.Columns[0].DataPropertyName = "Name";
dgvInputs.Columns[1].DataPropertyName = "Prompt";
dgvInputs.Columns[2].DataPropertyName = "Type";
dgvInputs.Columns[3].DataPropertyName = "Width";
dgvInputs.Columns[4].DataPropertyName = "Default Value";
When the user finishes editing the table, I need to validate it. In particular, I need to test that the Type has been defined in each row, and that the Default Value is compatible with the Type.
The problem is, every test I've found for checking if the Type has been set has failed. When I later try to cast the value as MyType as part of testing the default value, I get an error. When I check the .Value property on the empty Type cell in the debugger, it shows a value of "{}".
Currently, I have this code for the test, in the Validating event for the datagridview itself. I have tried various other versions and they have also failed:
foreach (DataGridViewRow Row in dgvInputs.Rows) {
if (!Row.IsNewRow) {
// test other columns ...
DataGridViewComboBoxCell Cell = (DataGridViewComboBoxCell)(Row.Cells[2]);
if (Cell == null || Cell.Value as string == string.Empty) {
// Error ...
}
MyType PType = (MyType)(Cell.Value);
How can I test if a DataGridViewComboBox cell has not been set, and what is this value "{}"?
FYI - I am using VS 2008, and .Net 3.5 SP1. Not my choice. Just what is available to me.
There are a couple problems with this code.
First, D.ValueType = typeof(MyType); is incorrect because from what I see, you are binding to int field. Just remove that line, ValueType will be inferred from the data source.
Now, the main issue. When binding to a data table, the non entered value is represented by DBNull.Value. I would suggest you checking for both null and DBNull.Value. When entered, the value type in your case will be int, but you can safely unbox it to MyType.
The code should be something like this
//...
var value = Row.Cells[2].Value;
if (value == null || value == DBNull.Value)
{
// Error ...
}
else
{
var type = (MyType)value;
// Check if type contains a valid value ...
}

Combobox index and value of non continued index

Not Sure how to explain the situation but its something like this
I am fetching (INT)category_id and (VARCHAR)categories_code from database and trying to push data inside Combobox using Index(category_id) and Value(categories_code). Now my problem starts when database doesn't have continued number index Eg. 0,1,3 and it throws Exception
InvalidArgument=Value of '3' is not valid for 'index'.
Parameter name: index
My Code is something like this
String query = "SELECT * FROM `category`";
productCategory.Items.Insert(0, "--- SELECT ---");
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(id, name);
}
}
}
What can be the expected solutions for this?
Use a counter instead ?
int i = 1;
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(i++, name);
}
}
}
or why don't you just use Add method?
productCategory.Items.Add(name);
If you want to get category id of selected item, then you should use a class for that.Create a class that has two properties, CategoryId and CategoryCode. Then have a List<YourClass> populate it, set the DataSource, ValueMember and DisplayMember properties of combobox.
productCategory.DataSource = yourList;
productCategory.DisplayMember = "CategoryCode";
productCategory.ValueMember = "CategoryId";

C# SMO Select from Database

I have been racking my brain trying to figure out how to execute a SELECT from Table using SMO in C# and returning that value to a string item.
I have seen multiple posts of how I can run a SQL script from within C# which is not what I want to do. Here is the code I have so far
public static void GetDealerInfo()
{
Server databaseServer = new Server(dbServer);
try
{
databaseServer.ConnectionContext.LoginSecure = dbSecure;
databaseServer.ConnectionContext.Login = dbUser;
databaseServer.ConnectionContext.Password = dbPass;
databaseServer.ConnectionContext.Connect();
sDealerName = databaseServer.ConnectionContext.ExecuteWithResults("USE DATABASE Select DataValue from TABLE where KEYField = 'DealershipName'").ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
if (databaseServer.ConnectionContext.IsOpen)
{
databaseServer.ConnectionContext.Disconnect();
}
}
}
I also have a string called sDealerName which is where I want to pull, all I am getting is
sDealerName = System.Data.DataSet
Can anyone point me in the correct direction?
UPDATE:
Here is the code to get it going or at least what worked for me
try
{
databaseServer.ConnectionContext.LoginSecure = dbSecure;
databaseServer.ConnectionContext.Login = dbUser;
databaseServer.ConnectionContext.Password = dbPass;
databaseServer.ConnectionContext.DatabaseName = dbDatabase;
databaseServer.ConnectionContext.Connect();
DataSet dsName = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from ABSetup where KEYField = 'DealershipName'");
sDealerName = dsName.Tables[0].Rows[0][0].ToString();
DataSet dsNum = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from ABSetup where KEYField = 'ABOfficeCID'");
sDealerNumber = dsNum.Tables[0].Rows[0][0].ToString();
}
Change your code to:
DataSet ds = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from TABLE where KEYField = 'DealershipName'");
The "USE DATABASE;", first, you may not need it. Second it, if you mean "USE MyDatabaseName;" , try it with a semi colon after the name.
More important to your question : then do a
Console.Writeline (ds.GetXml );
You'll then "see" the DataSet, the DataTable, the row inside the DataTable from which to "pluck" your scalar value.
string value = string.Empty;
if(null!=ds) {
if(null!=ds.Tables) {
if(ds.Tables.Count > 0) {
if(null!=ds.Tables[0].Rows) {
if(ds.Tables[0].Rows.Count > 0) {
if(null!=ds.Tables[0].Rows[0].Columns){
if(ds.Tables[0].Rows[0].Columns.Count > 0)
{
value = ds.Tables[0].Rows[0].Columns[0].Value;
}}}}}}}
"Count" may be "Length", I'm going from memory.
My code is untested from memory, so take it with a grain of salt.
You're calling ToString() on the object instance which is why you're getting the fullly qualified type name.
The value you're looking for will be inside a DataTable object within the DataSet. Run you're code again and break on the sDealerName line. Then using the magnifying glass tool click on that to open the dataset viewer and you'll be able to figure the rest out from there.

Selecting item in databound combobox

I believe this question is kinda new-bie, but I can't solve it in correct way.
Brief description:
I have an inherited from ComboBox class that does some data bindings in constructor:
var mdl = new Model();
ValueMember = "id";
DisplayMember = "unit";
DataSource = mdl.getUnits();
All good here. The combobox is filled by required data.
Then I have another form with a function editIngridient. The function is following;
public bool editIngridient(int id)
{
currentId = id;
var row = mdl.getIngridient(id);
txtIngridient.Text = (string)row["ingridient"];
cmbUnit.ID = (int)row["unitId"];
numNotifyQty.Value = (int) row["notifyQty"];
ShowDialog();
return true;
}
Now, when the form popups, textbox and number box filled by needed values, while combobox is filled by first value.
If I will run the combobox data bind function as the first line inside editIngridient function - all works good.
Please point me to my stupidity.
Thanks a lot!
YOu didnt say what is your dataSource, but I assume thats DataTable, so you can do it:
DataRowView rowData = comboBox1.SelectedItem as DataRowView;
int id = Convert.ToInt32(rowData["id"]);
string name = rowData["unit"].ToString();

Categories