Load a specific row as default item in combobox - c#

I fill combo-box with a data from database Access but my question is how can I put a specific row in database filled as a Default item in combo-box with C#?
gerant remplirlistgerant = new gerant();
foreach (gerant ligne in remplirlistgerant.getinfogerant())
{
cmbgerant.Items.Add(ligne.CIN_GERANT + " - " + ligne.NOM_GERANT + " - " + ligne.PRENOM_GERANT);
}

Hope I know yours,
Example if ligne.CIN_GERANT = "aaa" the current row will be selected.
gerant remplirlistgerant = new gerant();
foreach (gerant ligne in remplirlistgerant.getinfogerant())
{
cmbgerant.Items.Add(ligne.CIN_GERANT + " - " + ligne.NOM_GERANT + " - " + ligne.PRENOM_GERANT);
// Example if ligne.CIN_GERANT = "aaa" then select this row.
if (ligne.CIN_GERANT == "aaa" )
{
cmbgerant.SelectedIndex = cmbgerant.Items.Count - 1;// Item just added
}
}

Related

Determine Windows Update classification

From the Windows Update COM Library (WUAPILib) I have access to the IUpdate interface however I don't see of any way to use to get the update classification (Critical, Important, Optional) to group updates in the same way like the Windows Update UI in Control Panel does.
With the help of the IUpdate, you can get the IcategoryCollection from the Update ID.
Now, the first ICategory stores the classification of update type for the OS. Do pay special attention to the line where comment is placed:
Console.WriteLine("Patch name = " + ic.Name.ToString());
// In the ICategory collection, first element ICategory stores information of "Update Classification";
// whereas second Icategory element stores the product type information.
Test Code:
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
uSearcher.Online = false;
ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
Console.WriteLine("Found " + sResult.Updates.Count + " updates" + Environment.NewLine);
foreach (IUpdate update in sResult.Updates)
{
Console.WriteLine();
Console.WriteLine("Required update " + update.KBArticleIDs[0].ToString() + " is installed...");
Console.WriteLine("Update ID = "+update.Identity.UpdateID);
ICategoryCollection icc = update.Categories;
foreach (ICategory ic in icc)
{
Console.WriteLine("Patch description = " + ic.Description.ToString());
Console.WriteLine("Patch category = " + ic.CategoryID.ToString());
Console.WriteLine("Patch Type = " + ic.Type.ToString());
Console.WriteLine("Patch name = " + ic.Name.ToString());
// only first ICategory element stores the patch name,
// which reveals the Classification information
}
}
Sample Output:

changing two dropdownlists selected item from sql table but both get same selected value

I have two dropdowns initializing from same sql table:
ddlETCsc1.Items.Clear();
ddlETCsc2.Items.Clear();
foreach (var PSiteContacts in ContactsAdapter.GetPSiteContacts(Cus_Id))
{
var item = new System.Web.UI.WebControls.ListItem();
item.Text = PSiteContacts.name + " / " + PSiteContacts.phone;
item.Value = PSiteContacts.name + " / " + PSiteContacts.phone;
item.Attributes.Add("data-subtext", PSiteContacts.con_type);
ddlETCsc1.Items.Add(item);
ddlETCsc2.Items.Add(item);
}
ddlETCsc1.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Nothing Selected", "0"));
ddlETCsc2.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Nothing Selected", ""));
I am changing there selected item from sql table columns SContact1 and Scontact2 these have different data but both get same selected item:
ddlETCsc1.SelectedValue = reader["SContact1"].ToString();
ddlETCsc2.SelectedValue = reader["SContact2"].ToString();
I can see by addiong breakpoints that ddlETCsc1 gets correct value first but when ddlETCsc2 value changes the ddlETCsc1 get same value as ddlETcsc2.
It works fine for first time(i have dropdowns in bootstrap modal) but when i adds new contact(button on modal that opens another modal to add contact and after adding opens previous modal and also initialize the dropdowns again with new values and fetch values from sql) then the selected value not work as expected
Any help will be appreciated. Thanks in advance
The reason is because when you add item from your ContactsAdapter iteration, you refer to the same item (same ListItem) reference for each item in ddlETCsc1 and ddlETCsc2 (except for your "0" and "" later on). Try to change your code to:
ddlETCsc1.Items.Clear();
ddlETCsc2.Items.Clear();
foreach (var PSiteContacts in ContactsAdapter.GetPSiteContacts(Cus_Id))
{
var item1 = new System.Web.UI.WebControls.ListItem();
item1.Text = PSiteContacts.name + " / " + PSiteContacts.phone;
item1.Value = PSiteContacts.name + " / " + PSiteContacts.phone;
item1.Attributes.Add("data-subtext", PSiteContacts.con_type);
ddlETCsc1.Items.Add(item1);
var item2 = new System.Web.UI.WebControls.ListItem();
item2.Text = PSiteContacts.name + " / " + PSiteContacts.phone;
item2.Value = PSiteContacts.name + " / " + PSiteContacts.phone;
item2.Attributes.Add("data-subtext", PSiteContacts.con_type);
ddlETCsc2.Items.Add(item2);
}
ddlETCsc1.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Nothing Selected", "0"));
ddlETCsc2.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Nothing Selected", ""));
To create two different references (albeit having the same initial value) for each item inserted in the ddlETCsc1 and ddlETCsc2

c# List inside list XML Linq

I have the following statement
xdoc.Descendants("Father").Select(p => new
{
Son1 = (string)p.Element("Son1").Value,
Son2 = (string)p.Element("Son2").Value,
Son3= (string)p.Element("Son3").Value,
Son4 = (string)p.Element("Son4").Value,
Son5 = (string)p.Element("Son5").Value
}).ToList().ForEach(p =>
{
Response.Write("Son1= " + p.Son1 + " ");
Response.Write("Son2=" + p.Son2 + " ");
Response.Write("Son3=" + p.Son3 + " ");
Response.Write(("Son4 =") + p.Son4 + " ");
Response.Write(("Son5 =") + p.Son5 + " ");
Response.Write("<br />");
});
and it works fine as long as i have only one instance of each son , the problem is that i have multiple instances of Son5, and i donĀ“t know how to put Son5 inside of a list
Here is my XML code Example:
If you have several elements of same type, then you should parse them to list or other collection:
var fathers = from f in xdoc.Descendants("Father")
select new {
Son1 = (string)f.Element("Son1"),
Son2 = (string)f.Element("Son2"),
Son3= (string)f.Element("Son3"),
Son4 = (string)f.Element("Son4"),
Son5 = f.Elements("Son5").Select(s5 => (string)s5).ToList()
};
Some notes:
Don't use .Value of XElement or XAttribute - you can cast element itself to appropriate data type without accessing its value. Benefits - less code, more reliable in case element is missing (you will not get NullReferenceException)
Consider to use int or int? as elemenent values if your elements contain integer values
If you have single Father element, then don't work with collection of fathers. Just get xml root and check whether it's null or not. After that you can create single father object.
Writing response
foreach(var father in fathers)
{
Response.Write($"Son1={father.Son1} ");
Response.Write($"Son2={father.Son2} ");
Response.Write($"Son3={father.Son3} ");
Response.Write($"Son4={father.Son4} ");
Response.Write(String.Join(" ", father.Son5.Select(son5 => $"Son5={son5}"));
Response.Write("<br />");
}
Try this:
xdoc.Descendants("Father").Select(p => new
{
Son1 = p.Element("Son1").Value,
Son2 = p.Element("Son2").Value,
Son3= p.Element("Son3").Value,
Son4 = p.Element("Son4").Value,
Sons5 = p.Elements("Son5").Select(element => element.Value).ToList()
}).ToList().ForEach(p =>
{
Response.Write("Son1= " + p.Son1 + " ");
Response.Write("Son2=" + p.Son2 + " ");
Response.Write("Son3=" + p.Son3 + " ");
Response.Write("Son4 =" + p.Son4 + " ");
p.Sons5.ForEach(son5 => Response.Write("Son5 =" + son5 + " "));
Response.Write("<br />");
});
That will create a list of Son5 within your list of items, which you can iterate in the ForEach with another ForEach.

ASP.NET SQL Query One of Many Columns Undefined

General Description: Single SQL query of multiple SQL databases (through joins) returns all but one item from all but one database. Item not being returned is joined via an item that can, and sometimes is, null.
Specific Description:
I am continuing development of an internal ticketing system for work. I just started with C#, SQL and web development about a month ago, so I am still wrapping my head around all of the interconnections and syntax of Jquery, SQL, C#, and MVC.
Currently I am trying to display an SQL query in a table to show brief information for our tickets to support members. I have everything being displayed except "CircuitDescription" which is a pretty important element in order for support to differentiate between circuits. It is coming through on the table as "undefined" which I have gathered is the JQuery response for an initialized variable. All other values are coming through on the web page.
Running the SQL query through Microsoft SQL Server Management Studio displays the column with the circuit description.
Disclaimer:
While searching for this I have seen posts discouraging multiple database queries, but this is how the program was written before so I want to keep my code as similar to what has been done so far as possible.
So if we could jump past the part where it is implied I am an idiot (as is my only experience asking questions on stackoverflow) that would be lovely.
If you help me solve this, and help me learn why what you suggest works, then you can feel free to imply or directly call me anything you like.
Code:
C# / SQL Query:
-The join statements are combining the lists by a numeric value from DB "Tickets" with a numeric value from the other databases. Those databases are holding 2 columns, the numeric value and a corresponding string description.
-The full outer join is combining the list by a numeric circuitID from the tickets to a numeric circuitID in the circuits database.
-The circuit database holds the circuit description I am struggling with.
-Some circuitID values are null, which I suspect may be why this is not working. The other join statements that I am receiving data in connection to are all not null.
public static async Task<List<Ticket>> GetAllTicketsForCustomerAsync(DBAccess db, int customerID)
{
var cmd = "select TicketID, Tickets.DateCreated, Tickets.DateResolved, Tickets.CustomerCircuitID, CircuitDescription, TicketTypeDesc, BillingStatusDescription, TicketStatusDescription " +
"from Tickets " +
"join TicketTypes on Tickets.TicketTypeID = TicketTypes.TicketTypeID " +
"join TicketStatusTypes on Tickets.TicketStatus = TicketStatusTypes.TicketStatus " +
"join TicketBillingStatusTypes on Tickets.BillingStatus = TicketBillingStatusTypes.BillingStatus " +
"full outer join CustomerCircuits on Tickets.CustomerCircuitID = CustomerCircuits.CustomerCircuitID " +
"where Tickets.CustomerID = " + customerID +
"order by Tickets.TicketID DESC";
var table = await db.ReadTableAsync(cmd);
return (from DataRow row in table.Rows select db.AssignFromRow<Ticket>(row)).ToList();
}
JQuery:
-Ternary operator for circDesc is to list any tickets without a circuitID as "NonSpecific" for their circuit description. Otherwise they should display the circuit description that is currently coming through as "Undefined"
function buildPartialCustomerTicketsTable(tickets) {
var table = "";
var maxSize = (tickets.length < 5) ? tickets.length : 5;
for (var i = 0; i < maxSize; i++) {
var t = tickets[i];
var circDesc = (t.CustomerCircuitID == null) ? "Nonspecific" : t.CircuitDescription;
var rowClass = ((i % 2) == 0) ? "listRowNormal" : "listRowAlternate";
table += "<tr class='" + rowClass + "'>"
+ "<td class='listElement'><a href='#' onclick='viewTicket(" + t.TicketID + ",true)'>update</a></td>"
+ "<td class='listElement'>" + t.TicketStatusDescription + "</td>"
+ "<td class='listElement'>" + formatDate(t.DateCreated) + "</td>"
+ "<td class='listElement'>" + formatDate(t.DateResolved) + "</td>"
+ "<td class='listElement'>" + circDesc + "</td>"
+ "<td class='listElement'>" + t.TicketTypeDescription + "</td>"
+ "<td class='listElement'>" + t.BillingStatusDescription + "</td>"
+ "<td class='listElement'>" + t.TicketID + "</td>"
+ "</tr>";
}
return table;
}
Requested Code:
public T AssignFromRow<T>(DataRow row) where T : new()
{
var rec = new T();
this.AssignFromRow(row, rec);
return rec;
}
public void AssignFromRow(DataRow row, object rec)
{
if (row == null || rec == null)
{
return;
}
// Look at all of the properties in the record
PropertyInfo[] recprops = rec.GetType().GetProperties();
foreach (PropertyInfo pi in recprops)
{
// default the sql column name to the property name
string columnName = pi.Name;
// skip any read only parameters
if (!pi.CanWrite)
{
continue;
}
// Check for a mapping attribute. This attribute can change the name of the table column name from the default.
var customAttrs = pi.GetCustomAttributes(typeof(MappingAttribute), false);
if (customAttrs.Length > 0)
{
var mapping = (MappingAttribute)customAttrs[0];
if (!string.IsNullOrEmpty(mapping.ColumnName))
{
columnName = mapping.ColumnName;
}
}
// If the row does not have this element name then skip it
if (!row.Table.Columns.Contains(columnName))
{
continue;
}
// If the DataRow has a value with the same name, and it is not null, then assign it
object dbval = row[columnName];
if (dbval != null && !(dbval is DBNull))
{
pi.SetValue(rec, dbval, null);
}
}
}

remove spaces between columns exported to textfile

I am using c# windows application to get data from database and display on datagridview and exporting to text file
I want to remove empty spaces between below 4 columns .
2
vehicle control services ltd
Brom
Malkit
i get 2 vehicle control services ltd brom mal, but i want it to be like 2vehicle control services ltdBromMlkit
this is my code.
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([Claimant Name] +' ',30) " +
" , left([Claimant Address1] +' ',30) " +
" , left([Claimant Address2] +' ',30) as ClaimantAddress2 " +
" , left([Claimant Address3] +' ',30) as
exporting to text file code
if (obj == null || obj == Convert.DBNull)
return "";
// if string has no ','
if (obj.ToString().IndexOf(",") == -1)
return obj.ToString();
// remove backslahes
return "\"" + obj.ToString() + "\"";
}
private void ExportDatatviewToCsv(string iFilename, DataView dv)
{
// Open output stream
StreamWriter swFile = new StreamWriter(iFilename);
// Rows of Data
foreach (DataRowView rowData in dv)
{
string[] colData = new string[dv.Table.Columns.Count];
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
object obj = rowData[i];
colData[i] = GetWriteableValueForCsv(obj);
}
// Write data in row
swFile.WriteLine(string.Join(" ", colData));
}
// Close output stream
swFile.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (myDataset == null)
{
return;
}
if (myDataset.Tables[0].Rows.Count == 0)
{
return;
}
DataView vwExport = new DataView(myDataset.Tables[0]);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "TXT file|*.txt";
sfd.FileName = "ee " + ".txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
if (sfd.FileName != "")
{
ExportDatatviewToCsv(sfd.FileName, vwExport);
MessageBox.Show("File has been saved as: " + Environment.NewLine + sfd.FileName + Environment.NewLine + Environment.NewLine + "NB: This dataset has been ordered by t_reference in ascending order. If being combined with an existing dataset - that dataset will also need to be sorted in this way.", "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Just to make it clear what I think you are asking...
You currently get this for each line:
2 vehicle control services ltd brom mal
but you want it like this for each line (which let me point out makes absolutely no sense at all, it doesn't look very usable):
2vehicle control services ltdBromMlkit
If that is the case then in your code just replace this line:
swFile.WriteLine(string.Join(" ", colData));
with this line:
swFile.WriteLine(string.Join("", colData));
Notice that it will now join the string with an empty string, rather than joining with the single space that you don't want.

Categories