I have to assign 16 images that are randomized in an array to pictureboxes. I came up with the idea of creating an imagelist and then assign them to the pictureboxes.
Is there a way to shorten this?
This is the code that I came up with:
For i = 0 To FotoArray.Length - 1
ImageList1.Images.Add(Image.FromFile(FotoArray(i)))
Next
PictureBox1.Image = ImageList1.Images(0)
PictureBox2.Image = ImageList1.Images(1)
PictureBox3.Image = ImageList1.Images(2)
PictureBox4.Image = ImageList1.Images(3)
PictureBox5.Image = ImageList1.Images(4)
PictureBox6.Image = ImageList1.Images(5)
PictureBox7.Image = ImageList1.Images(6)
PictureBox8.Image = ImageList1.Images(7)
PictureBox9.Image = ImageList1.Images(8)
PictureBox10.Image = ImageList1.Images(9)
PictureBox11.Image = ImageList1.Images(10)
PictureBox12.Image = ImageList1.Images(11)
PictureBox13.Image = ImageList1.Images(12)
PictureBox14.Image = ImageList1.Images(13)
PictureBox15.Image = ImageList1.Images(14)
PictureBox16.Image = ImageList1.Images(15)
and also for this
Is there a way to make the same for this labels?
Label1.Tag = FotoArray(0)
Label2.Tag = FotoArray(1)
Label3.Tag = FotoArray(2)
Label4.Tag = FotoArray(3)
Label5.Tag = FotoArray(4)
Label6.Tag = FotoArray(5)
Label7.Tag = FotoArray(6)
Label8.Tag = FotoArray(7)
Label9.Tag = FotoArray(8)
Label10.Tag = FotoArray(9)
Label11.Tag = FotoArray(10)
Label12.Tag = FotoArray(11)
Label16.Tag = FotoArray(12)
Label13.Tag = FotoArray(13)
Label15.Tag = FotoArray(14)
Label14.Tag = FotoArray(15)
You can make use of the OfType Linq extension method to help make this code succint such as:
Dim pictureBoxes As List(Of PictureBox) = Me.Controls.OfType(Of PictureBox).ToList()
For counter As Integer = 0 To pictureBoxes.Count - 1
Dim pb As PictureBox = pictureBoxes(counter)
pb.Image = ImageList1.Images(counter)
Next
From MSDN:
Filters the elements of an IEnumerable based on a specified type.
Related
i have to read rows of data from an excel file which has only a column and then i have to save the rows in a table in database .
In my project i have to use ClosedXML .dll .
I have search but i couldn't find an example .
Can you please help me?
Thanks
For the ClosedXML part, you can refer to the documentation at https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data
private static void Main()
{
List<String> categories;
List<String> companies;
ExtractCategoriesCompanies("NorthwindData.xlsx", out categories, out companies);
// Do something with the categories and companies
}
private static void ExtractCategoriesCompanies(string northwinddataXlsx, out List<string> categories, out List<string> companies)
{
categories = new List<string>();
const int coCategoryId = 1;
const int coCategoryName = 2;
var wb = new XLWorkbook(northwinddataXlsx);
var ws = wb.Worksheet("Data");
// Look for the first row used
var firstRowUsed = ws.FirstRowUsed();
// Narrow down the row so that it only includes the used part
var categoryRow = firstRowUsed.RowUsed();
// Move to the next row (it now has the titles)
categoryRow = categoryRow.RowBelow();
// Get all categories
while (!categoryRow.Cell(coCategoryId).IsEmpty())
{
String categoryName = categoryRow.Cell(coCategoryName).GetString();
categories.Add(categoryName);
categoryRow = categoryRow.RowBelow();
}
// There are many ways to get the company table.
// Here we're using a straightforward method.
// Another way would be to find the first row in the company table
// by looping while row.IsEmpty()
// First possible address of the company table:
var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address;
// Last possible address of the company table:
var lastPossibleAddress = ws.LastCellUsed().Address;
// Get a range with the remainder of the worksheet data (the range used)
var companyRange = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed();
// Treat the range as a table (to be able to use the column names)
var companyTable = companyRange.AsTable();
// Get the list of company names
companies = companyTable.DataRange.Rows()
.Select(companyRow => companyRow.Field("Company Name").GetString())
.ToList();
}
EDIT: The below only gets you a populated datatable. You'll then need to load that datatable into your database. You don't say which database this is, but for SQL Server you would use the SqlBulkCopy class (see definition, which also has an example).
Late to the party, but try this:
public static DataTable GetDataTableFromExcel(string path, string sheetname = "", bool hasHeader = true)
{
using (var workbook = new XLWorkbook(path))
{
IXLWorksheet worksheet;
if (string.IsNullOrEmpty(sheetname))
worksheet = workbook.Worksheets.First();
else
worksheet = workbook.Worksheets.FirstOrDefault(x => x.Name == sheetname);
var rangeRowFirst = worksheet.FirstRowUsed().RowNumber();
var rangeRowLast = worksheet.LastRowUsed().RowNumber();
var rangeColFirst = worksheet.FirstColumnUsed().ColumnNumber();
var rangeColLast = worksheet.LastColumnUsed().ColumnNumber();
DataTable tbl = new DataTable();
for (int col = rangeColFirst; col <= rangeColLast; col++)
tbl.Columns.Add(hasHeader ? worksheet.FirstRowUsed().Cell(col).Value.ToString() : $"Column {col}");
Logger("started creating datatable");
rangeRowFirst = rangeRowFirst + (hasHeader ? 1 : 0);
var colCount = rangeColLast - rangeColFirst;
for (int rowNum = rangeRowFirst; rowNum <= rangeRowLast; rowNum++)
{
List<string> colValues = new List<string>();
for (int col = 1; col <= colCount; col++)
{
colValues.Add(worksheet.Row(rowNum).Cell(col).Value.ToString());
}
tbl.Rows.Add(colValues.ToArray());
}
Logger("finished creating datatable");
return tbl;
}
}
and call like this:
var datatable = GetDataTableFromExcel(fileName, sheetName);
If you're using (the excellent and free in its basic form) LinqPad, you can inspect the datatable using datatable.Dump();
Can you fix my problem? I try to insert data in table database oracle, but the data take from session array.
this code controller to insert data
int[] NoId = (int[])Session["Id"];
string[] NamaBarang = (string[])Session["namaBarang"];
string[] HargaSatuan = (string[])Session["harga"];
string[] JumlahBarang = (string[])Session["jumlah"];
string[] HargaTotal = (string[])Session["total"];
string[] Diskon = (string[])Session["disc"];
string[] DPP = (string[])Session["Dpp"];
string[] PPN = (string[])Session["Ppn"];
MPMISTAX_DTLMASUK itemA = new MPMISTAX_DTLMASUK();
itemA.KD_PPN = "2";
itemA.KDUNIT = Kategori;
itemA.KODE_SUPP = "M2Z";
itemA.NOFAK = nomorFaktur;
itemA.KDFAK = kodeFaktur;
itemA.VKODECABANG = KodeMain;
item.TAHUN = TanggalFak.Year;
itemA.RETUR = "";
itemA.NMBRG = NamaBarang[0];
itemA.HRGSAT = HargaSatuan[0];
itemA.NPWP = npwpPenjual;
itemA.NODOK = "-";
dbContext.MPMISTAX_DTLMASUK.Add(itemA);
dbContext.SaveChanges();
I try using that code, but its error. I Hope you can help my problem. Thank you
What is the datatype of
itemA.NMBRG?
if it's long please convert the NamaBarang[0] to long datatype before assigning. Like
itemA.NMBRG = (long)NamaBarang[0];
Hope this helps!!
You are trying to assign string to a feild which is of type long .Parse the string to long for feild NMBRG.
itemA.NMBRG = (long)NamaBarang[0];
My code below won't compile, the error message saying that PDM is not declared. I'm trying to call a SQL Server stored procedure from vb.net, and the code I have seems to match similar examples that I've found. Why doesn't the PDM part work for me?
Public Function ReturnPointSource(ByVal PlantName)
Dim TempList = New ArrayList
Dim sqlDR As SqlClient.SqlDataReader = PDM.Data.SqlHelper.ExecuteReader(GLOBALS.ConnectionString, "sp_readLocation")
If sqlDR.HasRows Then
While sqlDR.Read()
Dim Loc As New Location
Loc.strFID = sqlDR(0)
Loc.strFeature = sqlDR(1).ToString
Loc.intPlantNo = sqlDR(2).ToString
Loc.strPlantName = sqlDR(3).ToString
Loc.strMunicipality = sqlDR(4).ToString
Loc.strRegion = sqlDR(5).ToString
Loc.strOperator = sqlDR(6).ToString
Loc.strDistrict = sqlDR(7).ToString
Loc.strWatercourse = sqlDR(8).ToString
Loc.dblCapacity = sqlDR(9).ToString
Loc.dblPopulation = sqlDR(10).ToString
Loc.strOwnership = sqlDR(11).ToString
Loc.strOwnerClass = sqlDR(12).ToString
Loc.strCofNum = sqlDR(13).ToString
Loc.strComments = sqlDR(14).ToString
Loc.dblLatitude = sqlDR(15).ToString
Loc.dblLongitude = sqlDR(16).ToString
Loc.strSource_Point = sqlDR(17).ToString
Loc.intSeverity = sqlDR(18).ToString
Loc.dblSafe_buffer_distance_m = sqlDR(19).ToString
TempList.Add(Loc)
End While
End If
Return TempList
End Function
If you've taken that directly from an example then PDM would be something that they have defined themselves. It's not something that is part of the .NET Framework. I'm guessing that PDM is the author and SqlHelper is a class in their PDM.Data namespace.
If you want to get a data reader then you create a SqlCommand and then call ExecuteReader on it. That is what that PDM.Data.SqlHelper will be doing internally.
I am trying to add array in an array i.e 2d array, while I am trying it throws this error:
List index out of bound 0
I am trying at this line:
df_depts_obs[df_mk_index] = departmentobs_columns;
private void initializeInconsistentRecommendations() {
recmn_qty = new List<Integer>();
String mk_unique_Data;
Integer bookmark;
bookmark=0;
mk_unique_Data='';
totalCount = 0;
inconsistentRecommendations = new List<AA_Recommendations__c>();
inconsistentAccessorys = new List<AA_Accessory__c>();
df_depts = new List<AA_DepartmentObservation__c>();
df_depts_obs = new List<List<AA_DepartmentObservation__c>>();
df_depts_recmds = new List<List<AA_DepartmentRecommendation__c>>();
df_depts_prds = new List<List<AA_Recommendations__c>>();
String df_mk_unique_dept='';
Integer df_mk_index=-1;
departmentRecommendations_data = new List<AA_DepartmentRecommendation__c>();
List<AA_DepartmentObservation__c>departmentObservations = [SELECT Id, Name, Observation_ID__c,Department_ID__r.Name,Observation_ID__r.Observation__c FROM AA_DepartmentObservation__c
WHERE Department_ID__r.Assessment__c = :assessment.Id LIMIT 10];
if (departmentObservations.size() > 0) {
for (integer index = 0; index < departmentObservations.size(); index++ ) {
AA_DepartmentObservation__c departmentObservation = departmentObservations[index];
//df_depts.add(departmentObservation); // FOR DEPARTMNET HEADING
if(!df_mk_unique_dept.contains((String)departmentObservations[index].Department_ID__r.Name)){
df_mk_unique_dept += '<li>'+departmentObservations[index].Department_ID__r.Name+'</li>';
df_depts.add(departmentObservation); // FOR DEPARTMNET HEADING
df_mk_index = df_mk_index + 1;
}
List<AA_DepartmentObservation__c> departmentobs_columns = new List<AA_DepartmentObservation__c>();
departmentobs_columns.add(departmentObservation);
df_depts_obs[df_mk_index] = departmentobs_columns;
In Apex, you cannot use array notation [ ] to add objects, only set values for indexes in the array already exists.
You can either declare the size of the array so that it is initialized, or grow the array dynamically using the add method.
This example shows both options:
List<List<String>> stringList = new List<List<String>>(1);
List<String> innerListOne = new List<String> {'Red','Blue'};
List<String> innerListTwo = new List<String> {'One','Two'};
stringList[0] = innerListOne;
stringList.add(innerListTwo);
I am inserting data in the sql server.Here is the code:
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Int;
param[0].Value = "BSE";
formObjSqlConnection.SQLConnection.Executes("LPExch..DeleteVarMargin", param);
foreach (BseVar objBseVar in objListNseData)
{
currentIndex++;
param = new SqlParameter[10];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Char;
param[0].Value = "BSE";
param[1] = new SqlParameter();
param[1].ParameterName = "#Symbol";
param[1].SqlDbType = SqlDbType.Char;
param[1].Size = 10;
param[1].Value = objBseVar.Symbol;
param[2] = new SqlParameter();
param[2].ParameterName = "#Series";
param[2].SqlDbType = SqlDbType.Char;
param[2].Value = "EQ";
param[3] = new SqlParameter();
param[3].ParameterName = "#SecurityVar";
param[3].SqlDbType = SqlDbType.SmallMoney;
param[3].Value = objBseVar.SecurityVar;
param[4] = new SqlParameter();
param[4].ParameterName = "#IndexVar";
param[4].SqlDbType = SqlDbType.SmallMoney;
param[4].Value = 0;
param[5] = new SqlParameter();
param[5].ParameterName = "#VarMargin";
param[5].SqlDbType = SqlDbType.SmallMoney;
param[5].Value = objBseVar.IndexVar;
param[6] = new SqlParameter();
param[6].ParameterName = "#AdhocMargin";
param[6].SqlDbType = SqlDbType.SmallMoney;
param[6].Value = objBseVar.SecurityVar - objBseVar.IndexVar;
param[7] = new SqlParameter();
param[7].ParameterName = "#VarMarginRate";
param[7].SqlDbType = SqlDbType.SmallMoney;
param[7].Value = objBseVar.IndexVar;
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateOrAddCashVarMarginBSE", param);
if (Convert.ToInt32(1 / progressChange * currentIndex) <= 100)
objImportMaster.UpdateProgressBar(Convert.ToInt32(1 / progressChange * currentIndex));
}
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateCashVarMarginBSEScripNo");
Is there any other way i can insert the data in the database.The problem is that database is taking too much time to insert the data.Also i am updating the progressbar in other UI.
Is that the reason for slow insertion?
Can we use any other way to insert data.?
Right now you are sending every insert one at a time. That's slow. If you can change the database, look up table valued parameters and pass a table to your function so you can send all the records just once.
If you have direct access to a table, you can also use bulk copy.
If you are trying to insert many records then consider using bulk copy, it is quite fast.
An example is available here.