Array of objects [duplicate] - c#

This question already has answers here:
How to declare an array of objects in C#
(8 answers)
Closed last month.
Border[] _headerBorder = new Border[] {
new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
new Border{}, new Border{}, new Border{}, new Border{}, new Border{}
};
How can I shorten this type of declaration?

Shorten means what?
I would better go with the below If I need to create an array with 20 elements.
Border[] _headerBorder = new Border[20];
for (int i = 0; i < _headerBorder.Length; i++)
{
_headerBorder[i] = new Border();
}
Edit: As per the comment by #Rand random, you could also do it like this.
for (int i = 0; i < _headerBorder.Length; i++)
_headerBorder[i] = new ();

This is basically a for loop flattened into a single line of code:
var _headerBorder = Enumerable.Range(1, 20).Select(i => new Border()).ToArray();

Related

only 1 record coming instead of multiple records in the model in c#

im getting only 1 row multiple times instead of getting multiple records. same record getting multiple times in the datatable and model.
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT
Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
m.DeviceDate =Convert.ToDateTime(deviceDate);
m.Units =Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
Since the object is created before foreach, The object will be replaced with new entries all the time. Add Trans_energycons_ReportModel m = new Trans_energycons_ReportModel(); inside foreach
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
//Create object here
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
m.DeviceDate = Convert.ToDateTime(deviceDate);
m.Units = Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);

how to initialize multiple objects at once in c#

I need to initialize multiple objects like this.
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt4 = new DataTable();
Is there a way to initialize them as
DataTable dt1, dt2, dt3, dt4 = new DataTable();
If I use above, there are no compile errors but there are runtime errors says An Object reference not set to an instance.
How can I achieve this.
No, thereĀ“s no such way, you have to initialize them one by one.
Your error appears because dt1 to dt3 are initialized to null, only dt4 has a value. Thus doing anything with d1 will throw a NullReferenceException.
But you can do so in a single line:
DataTable t1 = new DataTable(), t2 = new DataTable(), t3 = new DataTable(), t4 = new DataTable();
Even better would be a list/array:
var tables = new[] { new DataTable(), new DataTdable(), new DataTable(), new DataTable() };
or even
var tables = Enumerable.Range(0, 4).Select(x => new DataTable());

add dynamic Multi View from database

i try to make an examining system so the admin up lode the question and the choices and the answers i wont to display in user side the question and the chooses in Multi View each view have a question and 3 Radio Button one for each chois
my code only bring me the last question in the table
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM exam WHERE exam_name='" + Request.QueryString["examid"] + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
View view = new View();
Label label = new Label();
RadioButton RadioButtonA = new RadioButton();
RadioButton RadioButtonB = new RadioButton();
RadioButton RadioButtonC = new RadioButton();
foreach (DataRow dr in dt.Rows)
{
label.Text = dr["qustion"].ToString();
RadioButtonA.Text= dr["cha"].ToString();
RadioButtonB.Text = dr["chb"].ToString();
RadioButtonC.Text = dr["chc"].ToString();
view.Controls.Add(label);
view.Controls.Add(RadioButtonA);
view.Controls.Add(RadioButtonB);
view.Controls.Add(RadioButtonC);
m1.Views.Add(view);
}
if (!IsPostBack)
{
m1.ActiveViewIndex = 1;
}
con.Close();
You create the instance outside the loop so every time when the program enters the loop. It only rewrites the text of existing controls instead of creating new ones.That's why it seems like only the last question remains.
What you want should be like
View view;
Label label;
RadioButton RadioButtonA, RadioButtonB, RadioButtonC;
foreach (DataRow dr in dt.Rows)
{
view = new View();
label = new Label();
RadioButtonA = new RadioButton();
RadioButtonB = new RadioButton();
RadioButtonC = new RadioButton();
label.Text = dr["qustion"].ToString();
RadioButtonA.Text= dr["cha"].ToString();
RadioButtonB.Text = dr["chb"].ToString();
RadioButtonC.Text = dr["chc"].ToString();
view.Controls.Add(label);
view.Controls.Add(RadioButtonA);
view.Controls.Add(RadioButtonB);
view.Controls.Add(RadioButtonC);
m1.Views.Add(view);
}

Add extra column and value to excel file before sending to SQL Server using C#

I am uploading an Excel file and inserting the data into SQL Server. But the issues is that before I send the Excel data to SQL Server, I want to add an extra column and value before sending.
Here is the code I tried:
using (OleDbConnection exel_con = new OleDbConnection(conString))
{
exel_con.Open();
string sheet1 = exel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[12] { new DataColumn("Full Name", typeof(string)),
new DataColumn("Email Address", typeof(string)),
new DataColumn("ID Type",typeof(string)),
new DataColumn("ID Number", typeof(string)),
new DataColumn("Gender",typeof(string)),
new DataColumn("Date of Birth", typeof(DateTime)),
new DataColumn("Nationality",typeof(string)),
new DataColumn("Married Status", typeof(string)),
new DataColumn("Join Date", typeof(DateTime)),
new DataColumn("Position",typeof(string)),
new DataColumn("Salary/Wages Frequency", typeof(string)),
new DataColumn("Salary/Wages Amount",typeof(int))
});
// Where I tried to add new column
dtExcelData.Columns.Add("AdminId", typeof(int));
foreach (DataRow row in dtExcelData.Rows)
{
// Where I tried to add new value to the column.
row["AdminId"] = 1;
}
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", exel_con))
{
oda.Fill(dtExcelData);
}
exel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["PayrollSystem"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
// Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Employee";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("AdminId", "AdminId");
sqlBulkCopy.ColumnMappings.Add("Full Name", "FullName");
sqlBulkCopy.ColumnMappings.Add("Email Address", "Email");
sqlBulkCopy.ColumnMappings.Add("ID Type", "IdType");
sqlBulkCopy.ColumnMappings.Add("ID Number", "IdNumber");
sqlBulkCopy.ColumnMappings.Add("Gender", "Gender");
sqlBulkCopy.ColumnMappings.Add("Date of Birth", "DateOfBirth");
sqlBulkCopy.ColumnMappings.Add("Nationality", "Nationality");
sqlBulkCopy.ColumnMappings.Add("Married Status", "MaritalStatus");
sqlBulkCopy.ColumnMappings.Add("Join Date", "JoinDate");
sqlBulkCopy.ColumnMappings.Add("Position", "Position");
sqlBulkCopy.ColumnMappings.Add("Salary/Wages Frequency", "SalaryFrequency");
sqlBulkCopy.ColumnMappings.Add("Salary/Wages Amount", "SalaryAmount");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
Please any help to solve this problem will be highly appreciated.
You should add the values to the new column AFTER you Fill() the DataTable. Until you fill it, it doesn't have any rows to loop through.
In fact, you should add the new column after you fill the DataTable since you are going to use SELECT * to fill it, and therefore the columns in the Excel have to match the columns in the DataTable.
So, fill the DataTable first. Then add the new column and values.

Dynamic table options

I`m creating a dynamic HTML Table, the table content is from the database.
I think I can do it - but I have 2 question:
How I add a <th> to each column? I want to name to columns I have (CustomerId,ProductId, etc).
How can I click on a specific row?
I want to click on a row and to be directed to a different page.
Note - I'm, not allowed to use DataTable - just HTML Table control.
This is my code:
string SQL_Order_View = "SELECT * FROM Orders";
SqlCommand SQLcmdOrders = new SqlCommand(SQL_Order_View, Conn);
Conn.Open();
SqlDataReader myOrders = SQLcmdOrders.ExecuteReader();
while(myOrders.Read())
{
TableRow tr = new TableRow();
TableCell tdCustomerId = new TableCell();
TableCell tdProductId = new TableCell();
TableCell tdPrice = new TableCell();
tdCustomerId.Text = myOrders["CustomerId"].ToString();
tdProductId.Text = myOrders["ProductId"].ToString();
tdPrice.Text = myOrders["Price"].ToString();
tr.Cells.Add(tdCustomerId);
tr.Cells.Add(tdProductId);
tr.Cells.Add(tdPrice);
tblOrders.Rows.Add(tr);
}
Conn.Close();
1.How I add a to each column
// Create a TableHeaderRow.
TableHeaderRow headerRow = new TableHeaderRow();
// Create TableCell objects to contain
// the text for the header.
TableHeaderCell headerTableCell1 = new TableHeaderCell();
TableHeaderCell headerTableCell2 = new TableHeaderCell();
TableHeaderCell headerTableCell3 = new TableHeaderCell();
headerTableCell1.Text = "CustomerId";
headerTableCell2.Text = "ProductId";
headerTableCell3.Text = "Price";
// Add the TableHeaderCell objects to the Cells
// collection of the TableHeaderRow.
headerRow.Cells.Add(headerTableCell1);
headerRow.Cells.Add(headerTableCell2);
headerRow.Cells.Add(headerTableCell3);
// Add the TableHeaderRow as the first item
// in the Rows collection of the table.
tblOrders.Rows.AddAt(0, headerRow);
2.How can to click on a specific row
tr.Attributes["onclick"] = "<some javascript code here>";
string SQL_Order_View = "SELECT * FROM Orders";
SqlCommand SQLcmdOrders = new SqlCommand(SQL_Order_View, Conn);
Conn.Open();
SqlDataReader myOrders = SQLcmdOrders.ExecuteReader();
// adding header
TableHeaderRow headRow = new TableHeaderRow();
TableHeaderCell thCustomerId = new TableCell();
TableHeaderCell thProductId = new TableCell();
TableHeaderCell thPrice = new TableCell();
thCustomerID.Text = "Customer ID";
thProductId.Text = "Product ID";
thPrice.Text = "Price";
tblOrders.Rows.Add(headRow );
while(myOrders.Read())
{
TableRow tr = new TableRow();
TableCell tdCustomerId = new TableCell();
TableCell tdProductId = new TableCell();
TableCell tdPrice = new TableCell();
tdCustomerId.Text = myOrders["CustomerId"].ToString();
//tdProductId.Text = myOrders["ProductId"].ToString();
//create clickable----
HyperLink lnk= new HyperLink();
lnk.ID = myOrders["ProductId"].ToString();
lnk.NavigateUrl = "your url with some id here";
tdProductId.Controls.Add(lnk);
tdPrice.Text = myOrders["Price"].ToString();
tr.Cells.Add(tdCustomerId);
tr.Cells.Add(tdProductId);
tr.Cells.Add(tdPrice);
tblOrders.Rows.Add(tr);
}
Conn.Close();
Use TableHeaderCell.
Additional information: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.tableheadercell.aspx

Categories

Resources