I need to dynamically create controls and display some database values in them.
For now I did :
SqlCommand cmdBE = new SqlCommand("SELECT COUNT (type) FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%' ", con);
Int32 countBE = (Int32) cmdBE.ExecuteScalar();
Console.WriteLine("nb BE : " +countBE);
SqlCommand cmdBEName = new SqlCommand("SELECT codeArticleComposant FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%'", con);
SqlDataReader readerBE = cmdBEName.ExecuteReader();
if (readerBE.Read())
{
Console.WriteLine(readerBE["codeArticleComposant"].ToString());
int pointXBE = 20;
int pointYBE = 20;
panelBE.Controls.Clear();
panelBE.Focus();
for (int i = 0; i < countBE; i++)
{
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
pointYBE += 30;
}
readerBE.Close();
}
My problem is that if several Controls are created, "readerBE["codeArticleComposant"].ToString()" does not change.
How can I make it loop on the different results that I need ?
You actually need to keep reading until all the records are being read using While loop, so change your if to While like:
int i =0; // use local variable for generating controls unique names
While(readerBE.Read())
{
//............
//........... your code here
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
i++; // increment after each read
}
Related
I am trying to read the fields in an Excel document and store the values into respective variables using Binding List and export it to Sql Server 2008 Database
Following is the code which I Found Online
public void csv()
{
try
{
MyApp = new Excel.Application();
MyApp.Visible = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.ShowDialog();
MyBook = MyApp.Workbooks.Open(ofd.FileName);
MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
var lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
BindingList<ExportExcel> EmpList = new BindingList<ExportExcel>();
for (int index = 2; index <= lastRow; index++)
{
System.Array MyValues = (System.Array)MySheet.get_Range("A" + index.ToString(), "G" + index.ToString()).Cells.Value;
EmpList.Add(new ExportExcel
{
PersonName = MyValues.GetValue(1, 1).ToString(),
Product = MyValues.GetValue(1, 2).ToString(),
StartDate = Convert.ToDateTime(MyValues.GetValue(1, 3).ToString()),
ExpiresOn = Convert.ToDateTime(MyValues.GetValue(1, 4).ToString()),
DaysIssued = MyValues.GetValue(1, 5).ToString(),
TrialsIssued = MyValues.GetValue(1, 6).ToString(),
Contact = MyValues.GetValue(1, 7).ToString()
});
query = "EXEC dbo.proc_ImportExcel'" + PersonName + "', '" + Product + "','" + StartDate + "','" + DaysIssued + "','" + ExpiresOn + "','" + TrialsIssued + "','" + Contact + "'";
}
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am getting proper values in the line PersonName = MyValues.GetValue(1, 1).ToString(), and the values are not getting stored in variable personName whereas the the values are shown in line MyValues.GetValue(1, 1).ToString(),I am getting an error object reference not set to instance of an object.
Can anyone help me to solve this issue.
Thanks
I would like to recreate my list after it is updated (at allocate positions) so that it includes the new columns in the position table. Is this possible? How would I go about doing it?
I've tried clearing it and attempting to read the dataReader again, but with little success, will I have to rerun the SQL query?
public List<BidList> AllocateBids()
{
// Determine positions
string query =
"SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
"JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode='" + _plot + "'" +
"ORDER BY t2.market_access ASC, t1.datetime ASC";
var bidList = new List<BidList>();
var cmd = new MySqlCommand(query, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
var item = new BidList
{
OperatorId = dataReader["operator_id"] + "",
PlotId = dataReader["plot_id"] + "",
Position = dataReader["position"] + "",
Datetime = dataReader["datetime"] + "",
MarketAccess = dataReader["market_access"] + "",
};
bidList.Add(item);
}
// Allocate positions
for (var i = 0; i < bidList.Count; i++)
{
var position = i + 1;
query = "UPDATE bid SET position='" + position + "' WHERE operator_id='" + bidList[i].OperatorId +
"'";
var dbObject = new DbConnect();
dbObject.InsertBooking(query);
}
return bidList;
// Recreate list
//bidList.Clear();
//while (dataReader.Read())
//{
// var item = new BidList
// {
// OperatorId = dataReader["operator_id"] + "",
// PlotId = dataReader["plot_id"] + "",
// Position = dataReader["position"] + "",
// Datetime = dataReader["datetime"] + "",
// MarketAccess = dataReader["market_access"] + "",
// };
// bidList.Add(item);
//}
//CloseConnection();
//return bidList;
}
instead of recreate the list, if you're updating only 1 field, and it's the position one, why don't you reorder it like this:
// Allocate positions
for (var i = 0; i < bidList.Count; i++)
{
var position = i + 1;
bidList[i].Position = position;
query = "UPDATE bid SET position='" + position + "' WHERE operator_id='" + bidList[i].OperatorId +
"'";
var dbObject = new DbConnect();
dbObject.InsertBooking(query);
}
return bidList.OrderBy(bid => bid.Position);
bidList.OrderBy() will return the same List, ordered by the position values you just assigned it
I have a button on my Gridview:
<asp:Button ID="lnk_ship" runat="server" CssClass="btn-mini" Text="Ship Software" />
I am loading my Gridview from SQL, to a Class, then a DataBind() event,
protected void FilterResults(object sender, EventArgs e)
{
var shipments = new List<SoftShipments>();
DateTime dt1 = Convert.ToDateTime(Textbox1.Text);
DateTime dt2 = Convert.ToDateTime(Textbox2.Text);
string cvt1 = "'" + dt1.Year.ToString() + "-" + dt1.Month.ToString() + "-" + dt1.Day.ToString() + "'";
string cvt2 = "'" + dt2.Year.ToString() + "-" + dt2.Month.ToString() + "-" + dt2.Day.ToString() + "'";
string qry = null;
if (Showshipped.Checked)
{
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2;
}
else {
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2 + " and sft_shipped = 'No'";
}
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("softship"));
conn.Open();
SqlCommand cmd = new SqlCommand(qry, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
shipments.Add(new SoftShipments() { index = (int) dr["id"], softtitle = dr["sft_SoftTitle"].ToString(),
productID = dr["sft_ProductID"].ToString(), ver = dr["sft_Version"].ToString(),
custnam = dr["sft_CustName"].ToString(), title = dr["sft_Title"].ToString(),
comp = dr["sft_Company"].ToString(), shipAddr = dr["sft_ShipAddress"].ToString(),
dept = dr["sft_Dept"].ToString(), city = dr["sft_City"].ToString(), state = dr["sft_State"]
.ToString(), postalCd = dr["sft_PostalCd"].ToString(), country = dr["sft_Country"].ToString(),
email = dr["sft_Email"].ToString(), entry_date = dr["sft_Entry_Dt"].ToString(),
ship_date = dr["sft_Ship_Dt"].ToString(), shipped = dr["sft_Shipped"].ToString()
});
}
gdv_Ship.DataSource = shipments;
gdv_Ship.DataBind();
conn.Close();
}
I would like to load the Gridview with the button visible if the value "shipped = 'No' or not visible if 'Yes' ... just not quite certain where to add this code? Any assistance would be appreciated.
Regards,
You could subscribe to the databound event of the grid, and then show/hide the buttons in the template with a FindControl("controlName")
I have written a code to retrieve the id of the dynamic link button clicked by the user. But however, it is displaying all the link buttons' id.
Please check my code.
if (reader.HasRows)
{
while (reader.Read())
{
JobDesignation = reader.GetString(0);
JobDescription = reader.GetString(1);
NoOfVacancies = Convert.ToString(reader.GetInt32(2));
DatePosted = Convert.ToString(reader.GetDateTime(3)).Replace("00:00:00", "");
jobId = reader.GetString(4);
int tblRows = 1;
int tblCols = 1;
Table tbl = new Table();
PlaceHolder1.Controls.Add(tbl);
for (int i = 0; i < tblRows; i++)
{
readerrowcount = readerrowcount + 1;
TableRow tr = new TableRow();
tr.CssClass = "rowStyle1";
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
tc.CssClass = "cellStyle1";
System.Web.UI.WebControls.Label txtBox = new System.Web.UI.WebControls.Label();
txtBox.Text = "Job ID:" + jobId + "<br />" + "Job Designation:" + JobDesignation + "<br />" + "Job Description:" + JobDescription + "<br />" + "Vacancies:" + NoOfVacancies + "<br />" + "Ad Posted On:" + DatePosted + "<br />"+"";
tc.Controls.Add(txtBox);
tr.Cells.Add(tc);
System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
lbView.Text = "<br />" + "Apply for this Job";
lbView.OnClientClick = "return RedirectTo('" + id + "');";
lbView.ID = "linkButton" + readerrowcount;
ID = readerrowcount;
tc.Controls.Add(lbView);
tr.Cells.Add(tc);
}
tbl.Rows.Add(tr);
string query = "INSERT INTO EmployeeJobTagging VALUES('" +ID + "','" + id + "','"+jobId+"','"+JobDesignation+"')";
SqlCommand sqlCmd = new SqlCommand(query, con);
sqlCmd.ExecuteNonQuery();
}
ViewState["dynamictable"] = true;
} reader.NextResult();
}
Here i have two rows displayed and if the user clicks on the first
"apply for this job"
i want the ID to be "1" to be passed to database so that there will be only 1 row inserted into the EmployeeJobTagging table. but here both the rows are inserted with ID= 1 and 2 respectively.
Please find below.
Kindly provide me some help.
Well, I am doing a project on online movie ticket booking.
My problem is, I want to show the seating arrangement in a screen of a particular theater.
As in every row the number of seats can vary so what I have done is add a panel and in it a checkboxlist is dynamically added during runtime.
each checkboxlist represents a single row.
string s;
for (int i = 0; i < ds.Tables["row_id_no_of_seats"].Rows.Count; i++)
{
cbl = new CheckBoxList();
cbl.RepeatDirection = 0; //horizontal
cbl.RepeatLayout = 0; //table
cbl.RepeatColumns = (int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];
Panel1.Controls.Add(cbl);
for(int j=1;j<=(int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];j++)
{
s = ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString() + j.ToString(); //ex:A+1
cbl.Items.Add(s);
string query1 = "select booking_detail.row_id,booking_detail.column_id from booking_detail,booking where (booking_detail.booking_id=booking.booking_id) and (booking_detail.booking_date='" + bk_date + "') and (booking.booking_date='" + bk_date + "') and (booking.theatre_id=" + theatre_id + ") and (booking.screen_id=" + screen_id + ") and (booking.movie_id=" + movie_id + ") and (booking.show_start_time='" + show_start_time + "') and (booking.class_id=" + class_id + ")";
SqlCommand command1 = new SqlCommand(query1, connection);
adapter.SelectCommand = command1;
adapter.Fill(ds, "seat_booked_info");
// it checks and disables the seats which have been pre- booked.
for (int k = 0; k < ds.Tables["seat_booked_info"].Rows.Count;k++) {
if(ds.Tables["seat_booked_info"].Rows[k].ItemArray[0].ToString().Equals(ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString())) && (ds.Tables["seat_booked_info"].Rows[k].ItemArray[1].ToString().Equals(j.ToString())))
{
cbl.Items.FindByText(s).Selected=true;
cbl.Items.FindByText(s).Enabled = false;
}
}
ds.Tables["seat_booked_info"].Clear();
}
}
Now what I want is, how do I get the details of the checkbox which have been selected by the user as the checkboxlist are dynamically added to the panel?
You would use something like this:
foreach (Control c in Panel1.Controls)
{
CheckBoxList list = c as CheckBoxList;
if (c != null)
{
// Do something with the list
}
}