I am currently modifying an existing application, I am removing the old UI elements and replacing them with standard WinForms components. So this code is functional as it appears.
My code is passing the conditional IF check when it should not be. The text for each of the comboboxes is <Any> by default, so they should skip past the encapsulated code.
(When filters are selected, they replace the default text to select the correct parts of SQL query to return results)
Now for the bizarre part!
The text property is coming up as System.Data.DataRowView for some of my combobox.text. Originally, this happened for all of them but now the first check appears as <Any> as intended. (Although I didn't change anything at all)
As you can see in this screenshot of my code during debug. The pinned value of cbRegGroup.Text is System.Data.DataRowView but when I enter the list of properties and scroll down to the text property it is shown as <Any>.
I have cleaned and rebuilt my project... and consulted with a college but neither of us can work out why text value is appearing like a .ToString()'ed object.
I am at a loss at what to do next. Any suggestions?
private void LoadPupilView()
{
try
{
this.Cursor = Cursors.WaitCursor;
dgMain.Rows.Clear();
//now populate list view
String filter = "[surname] LIKE '" + SearchString + "%'";
if (!cbYearGroup.Text.Equals("<Any>"))
{
String YearGroupCode = null;
try
{
YearGroupCode = cbYearGroup.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(YearGroupCode))
filter = filter + " AND [yearGroup] LIKE '" + YearGroupCode + "'";
}
if (!cbRegGroup.Text.Equals("<Any>"))
{
String RegGroupCode = null;
try
{
RegGroupCode = cbRegGroup.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(RegGroupCode))
filter = filter + " AND [registrationGroup] LIKE '" + RegGroupCode + "'";
}
if (!cbHouse.Text.Equals("<Any>"))
{
String HouseGroupCode = null;
try
{
HouseGroupCode = cbHouse.SelectedValue.ToString();
}
catch { }
if (!String.IsNullOrEmpty(HouseGroupCode))
filter = filter + " AND [houseGroup] LIKE '" + HouseGroupCode + "'";
}
DataRow[] dataRows = tblPupils.Select(filter);
foreach (DataRow datarow in dataRows)
{
dgMain.Rows.Add(new object[] {
datarow[0].ToString(),
datarow[1].ToString() + " " + datarow[2].ToString(),
datarow[5].ToString(),
datarow[4].ToString(),
datarow[6].ToString(),
datarow[3].ToString()
});
}
}
catch (Exception err)
{
MessageBox.Show("Error : " + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Cursor = Cursors.Default;
}
}
I'm very interested in knowing why this seems to be inconsistent... why is the first conditional check passed? When the rest aren't although they are the same.
You need to set the DisplayMember property of the ComboBox to the name of the column you want to display.
Related
I have a question regarding combobox. Add first I try to add some items to classTimeComboBox by looping the array and it works. But when I try to combine the foreach looping with if condition and the combobox display nothing inside it. Can someone fix this for me?
Here is my database screenshot
(All table in the database is in "Short Text" type.)
private void classTimeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string ClassTime = classTimeComboBox.Text;
string ClassDate = classDateBox.Text;
string[] ClassName = { "CL01", "CL02", "CL03", "CL04", "CL05", "CL06", "CL07", "CL08", "CL09" };
if(classTimeComboBox.SelectedItem.ToString() == "08:00")
{
foreach (string x in ClassName)
{
cnnOleDB.Open();
checkAvailableClassRoom.CommandText = "Select * from Uploads where [ClassDate]='" + ClassDate + "' AND [ClassTime]='" + ClassTime + "' AND [ClassName]='" + x + "';";
checkAvailableClassRoom.Connection = cnnOleDB;
OleDbDataReader readDatabase = checkAvailableClassRoom.ExecuteReader();
if (readDatabase.Read() != true)
{
classNameComboBox.Items.Add(x);
}
else
{
}
cnnOleDB.Close();
}
}
}
The OleDbReader.Read() advances the reader to the next record and the method returns
true if there are more rows; otherwise, false.
So you should change the code, if you expect to have db more than one row, to this:
while (reader.Read())
{
var stringIdx = reader.GetOrdinal("<string Colum to display in combobox>");
classNameComboBox.Items.Add(reader.GetString(stringIdx));
}
If you only expect one row, or don't care about the number of rows you can change the while with the if you have with a small change:
if (readDatabase.Read() == true)
{
classNameComboBox.Items.Add(x);
}
I want to bind the combobox in c#.net windows application and that also the binded combobox I want in uppercase word.
Now, I bind the combobox successfully but the problem is that I didnt get any uppercase word in it.
Here is my code,
public void BindDropdownList(ComboBox f_dropdown, string tblname, string display_field, string value_fldName, string wherecondition = "")
{
try
{
string qrysel = "select " + value_fldName + "," + display_field + " from " + tblname + " " + wherecondition + "";
DataTable dt_list_detail = new DataTable();
dt_list_detail = clsObjDataAccess.GetDataTable(qrysel);
if (dt_list_detail != null)
{
if (dt_list_detail.Rows.Count > 0)
{
f_dropdown.DataSource = dt_list_detail;
f_dropdown.DisplayMember = display_field;
f_dropdown.ValueMember = value_fldName;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I tried many things but didnt work like
f_dropdown.DataSource = dt_list_detail;
f_dropdown.DisplayMember = display_field.ToUpper();
f_dropdown.ValueMember = value_fldName.ToUpper();
next
f_dropdown.DisplayMember = display_field.ToString().ToUpperInvariant();
and many other thing also but the same thing happing with me that is not working in upper case word.
You could do the following.
f_dropdown.Format += (s, arg) =>
{
arg.Value = arg.Value.ToString().ToUpperInvariant();
};
Test Collection
_persons = new List<Person>
{
new Person(){Id=1, Name = "Anu"},
new Person(){Id=1, Name = "Jia"},
};
f_dropdown.DataSource =
f_dropdown.DisplayMember = "Name";
f_dropdown.Format += (s, arg) =>
{
arg.Value = arg.Value.ToString().ToUpperInvariant();
};
Output
I'd like to search through the tree in CATIA, and return the names of the parts in the tree using C#. My current code is as follows:
private void Search(object sender, EventArgs e)
{
string searchName = OriginalBox.Text;
string name;
INFITF.SelectedElement part;
//CATIA.StartCommand("Search");
try
{
Sel.Search("Name=" + searchName + "*, all");
for (int i = 1; i <= Sel.Count; i++)
{
part = Sel.Item(i);
name = part.get_Name();
MessageBox.Show(i.ToString() + " : " + name);
}
}
catch (IOException ex)
{
if (ex.Source != null)
MessageBox.Show(ex.Source);
throw;
}
}
The MessageBox displays "CATIASelectedElement45". I am receiving the message "ERROR HRESULT E_FAIL has been returned from a call to a COM component." when assigning the Sel.Item(i) to part.
How can I access the part name using Selection.Search?
On Sel.Search("Name=" + searchName + "*, all"); you are searching for any object containing that name, if you would like to search exclusively for Part only, you should use a type search:
Sel.Search("(((((('Product Structure'.Part + FreeStyle.Part) + 'Assembly Design'.Part) + 'Part Design'.Part) + 'Generative Shape Design'.Part) + 'Functional Molded Part'.Part) + 'Process Applications'.Part);all");
//To get any search string, use search on Catia and copy it from there.
Also, to get the real value from selection inside your For use this:
Sel.Item(i).Value; // Object retrieved from selection
name = ((INFITF.AnyObject) Sel.Item(i).Value).get_Name(); // Object Name
Note that the SelectedElement class is just a middle class to abstract all kinds of objects into a selection. It contains some properties and methods that may be usefull sometimes though, such as Reference and LeafProduct.
Then instead of using Selection search I think it is ideal to loop through a specific type of feature like Bodies, Hybridbodies, Shapes..etc
While looping through it you can compare the item name value with your string value and store it.
Something like this:
int bodiesCount = Part.Bodies.count
for (int i = 1; i <= bodiesCount; i++)
{
string name = Part.Bodies.Item(i).Name;
if(name == TextBox.Text("your string value"))
{
Sel.Add(Part.Bodies.Item(i));
MessageBox.Show(i.ToString() + " : " + name);
}
}
You can try this:
Sel.Search ("Name=" + searchName + "* & CATPrtSearch,all");
for (int i = 1; i <= Sel.Count; i++)
{
MECMOD.Part selectedPart;
selectedPart = Sel.Item(i).Value;
name = selectedPart.get_Name();
MessageBox.Show(i.ToString() + " : " + name);
}
this is my first question in here.
So I have this app that connects to a remote database using Npgsql library.
I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.
Sorry about my english
public static NpgsqlConnection ConnectRemote()
{
try
{
remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
"Port = " + remoteData.port + "; " +
"User Id = " + remoteData.user + "; " +
"Password = " + remoteData.password + "; " +
"Database = " + remoteData.dataBase + "; ");
remoteConnection.Open();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
public static bool CheckRemote()
{
if (remoteConnection != null)
{
if (remoteConnection.FullState.Equals(ConnectionState.Open))
return true;
return false;
}
return false;
}
public bool AddNewProduct(Product product)
{
try
{
DBManager.ConnectLocal();
DBManager.ConnectRemote();
object[] parameters;
if (DBManager.CheckRemote())
{
if (!DBManager.isSyncronized)
{
DBManager.Syncronize();
}
parameters = new object[8];
parameters[0] = 1;
parameters[1] = product.id;
parameters[2] = product.description;
parameters[3] = (decimal)product.salePrice;
parameters[4] = (decimal)product.cost;
parameters[5] = product.minStock;
parameters[6] = product.providerName;
parameters[7] = product.category;
DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
}
else
{
string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
+ (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
parameters = new object[1];
parameters[0] = sql;
DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);
DBManager.isSyncronized = false;
}
parameters = new object[6];
parameters[0] = product.description;
parameters[1] = (decimal)product.salePrice;
parameters[2] = (decimal)product.cost;
parameters[3] = product.minStock;
parameters[4] = product.providerName;
parameters[5] = product.category;
DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
DBManager.DisconnectLocal();
DBManager.DisconnectRemote();
return true;
}
catch (Npgsql.NpgsqlException ex)
{
return false;
}
}
A few things -- one unrelated, and two related. I am hopeful that some combination of these will help.
First, the unrelated comment. The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings. I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query. Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.
If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database. If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused. Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.
If this doesn't work, try a trivial query. The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.
All three suggestions are reflected here:
public static NpgsqlConnection ConnectRemote()
{
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.ApplicationName = "Connection Tester";
sb.Host = remoteData.server;
sb.Port = remoteData.port;
sb.Username = remoteData.user;
sb.Password = remoteData.password;
sb.Database = remoteData.database;
sb.Pooling = false;
remoteConnection = new NpgsqlConnection(sb.ToString());
try
{
remoteConnection.Open();
NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
test.ExecuteScalar();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.