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.
Related
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
}
I have a datagridview in my winform and I select a row within the dgv - send an email. I need to write to a sql table that the email has been sent (Ack column) and date the email was sent. This text is not in the DGV. I am having trouble doing this with the code I have. It doesn't seem to do anything at all - I don't see anything in the debugger either.
Here is my code:
namespace TTIdB
{
public partial class OrdrProc : Form
{
public OrdrProc()
{
InitializeComponent();
salesOrdersDataGridView.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
}
private void btnAck_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection("Data Source=srv;Initial Catalog=db;Integrated Security=True"))
using (SqlCommand cmd = cn.CreateCommand())
{
foreach (DataGridViewRow row in salesOrdersDataGridView.SelectedRows)
{
cmd.CommandText = ("UPDATE table SET Ack = #Ack,DateAcknowledged = #DateAcknowledged WHERE orderNum = #Ordrnum");
cmd.Parameters.AddWithValue("#Ack", "Y");
cmd.Parameters.AddWithValue("#DateAcknowledged", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#Ordrnum", lblOrder.Text);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
try
{
//Must add Outlook Reference Object Library
Outlook.Application _app = new Outlook.Application();
Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = lblEmail.Text;
mail.Subject = "Order Acknowledgement for your PO " + lblPO.Text;
mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
mail.HTMLBody = "<HTML><BODY>";
mail.HTMLBody += "Thank you for your order!" + "<br />" + "<br />" + "Touchstone Order Number: " + lblOrder.Text +
"<br />" + "Touchstone Part Number: " + lblPN.Text + "<br />" + "Description:" + lblDesc.Text + "<br />" + "Customer Part Number: " + " " +
lblCpn.Text + "-" + " Revision: " + lblRev.Text + "<br />" + "Expected Ship Date: " + lblshp.Text +
"<br />" + "Quantity: " + lblQty.Text + "<br />" + "<br />" + "Regards," + "<br />" +
"<br />" + "Customer Service" + "<br />" + "Touchstone Technology, Inc." + "<br />" + "350 Mile Crossing Blvd." +
"<br />" + "Rochester, NY 14624" + "<br />" + "Phone: 585.458.2690";
mail.HTMLBody += "<p>Web: <a href='http://www.touchstn.com'>touchstn.com</a></p></body></html>";
mail.Display(true);
Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OrdrProc_Load(object sender, EventArgs e)
{
salesOrdersTableAdapter.SO(_TST_TWIDataSet1.SalesOrders);
}
private void salesOrdersDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex>-1)
{
DataGridViewRow row = salesOrdersDataGridView.Rows[e.RowIndex];
string cpn = "";
cpn = salesOrdersDataGridView.Rows[e.RowIndex].Cells["customerPart"].Value.ToString();
lblCpn.Text = cpn;
lblCpn.Visible = true;
string ordnum = "";
ordnum = salesOrdersDataGridView.Rows[e.RowIndex].Cells["orderNum"].Value.ToString();
lblOrder.Text = ordnum;
lblOrder.Visible = true;
string pnum = "";
pnum = salesOrdersDataGridView.Rows[e.RowIndex].Cells["partNum"].Value.ToString();
lblPN.Text = pnum;
lblPN.Visible = true;
lblPN.ForeColor = Color.FromArgb(0, 192, 0);
string desc = "";
desc = salesOrdersDataGridView.Rows[e.RowIndex].Cells["descript"].Value.ToString();
lblDesc.Text = desc;
lblDesc.Visible = true;
string quant= "";
quant = salesOrdersDataGridView.Rows[e.RowIndex].Cells["quant"].Value.ToString();
lblQty.Text = quant;
lblQty.Visible = true;
string cpo = "";
cpo= salesOrdersDataGridView.Rows[e.RowIndex].Cells["custPO"].Value.ToString();
lblPO.Text =cpo;
lblPO.Visible = true;
string rev = "";
rev = salesOrdersDataGridView.Rows[e.RowIndex].Cells["custRev"].Value.ToString();
lblRev.Text = rev;
lblRev.Visible = true;
lblRev.ForeColor = Color.FromArgb(0, 192, 0);
DateTime shp = DateTime.Parse(salesOrdersDataGridView.Rows[e.RowIndex].Cells["shipDate"].Value.ToString());
lblshp.Text = shp.ToString("MM/dd/yyyy");
lblshp.Visible = true;
string eml = "";
eml = salesOrdersDataGridView.Rows[e.RowIndex].Cells["email"].Value.ToString();
lblEmail.Text = eml;
lblEmail.Visible = true;
}
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
}
}
I am using VS2015
UPDATE with this code: I am now able to enter in the ForEach loop and it does write to the table, but now, it inserts the text (Ack and Date) to all of the rows and not exclusively to the one I selected
Another Update: I was able to get it working - the code above should be ok - hope it helps someone in the future
Thank you in advance
Please add SqlConnection object in SqlCommand parameter. Follow the code:
SqlConnection cn = new SqlConnection("Data Source=srv;Initial Catalog=db;Integrated Security=True"))
{
foreach (DataGridViewRow row in salesOrdersDataGridView.SelectedRows)
{
SqlCommand cmd = new SqlCommand("Insert into tbl (Ack,DateAcknowledged) Values (#Ack,#DateAcknowledged)",cn);
cmd.Parameters.AddWithValue("#Ack", "Y");
cmd.Parameters.AddWithValue("#DateAcknowledged", DateTime.Now.ToShortDateString());
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
It seems that you don't have selected rows over the datagrid view that's why the code does not step to the SQL command. you need to make sure that you select the rows you need to write ack for them on your table and check that your data grid allows selection.
My Problem as follows;
Last row of datagridview is always Focused, so when I click the btnSave of toolStripButton, I can not save the last row data to the database. How should I solve this problem? I know if I use the Button Control, I can solve this problem. But I want to know more:
private void btnSave_Click(object sender, EventArgs e)
{
dgvHead.EndEdit();
dgvHead.RefreshEdit();
dgvHead.Refresh();
dgvHead.Update();
dgvHead.LostFocus += new EventHandler(dataGridView1_LostFocus);
//dgvHead.ClearSelection();
//int id = 0;
//保存到数据库之前先判断一下主表是否有重复记录
string fno = txtfNo.Text.Trim();
string fname = txtPname.Text.Trim();
int orderqty = Convert.ToInt32(txtOrderQty.Text);
double orderc = Convert.ToDouble(txtOrderCoefficient.Text);
Image pic = pbchef.Image;
//主表的修改
string sql1 = "select count(1) from desProductAttach where fno='" + fno + "' and fno!='" + args["pNo"].ToString() + "' and fname='" + fname + "' and orderqty=" + orderqty + " and orderCoefficient=" + orderc + "";
int count = Convert.ToInt32(SqlHelp.GetValue(CommandType.Text, sql1));
if (count != 0)
{
MessageBox.Show("数据库中已经存在重复记录,请修改后重新录入!");
return;
}
string sql2 = #"update desProductAttach set fno='" + fno + "',fname='" + fname + "',orderqty=" + orderqty + ",orderCoefficient=" + orderc + " where id="+id+"";
SqlHelp.ExecuteNonQuery(CommandType.Text,sql2);
//子表的更新(通过数据源更新)
if (ds1.HasChanges())
{
SqlCommandBuilder cb = new SqlCommandBuilder(sda1);
sda1.Update(ds1.Tables[0]);
ds1.AcceptChanges();
// dgvHead.Update();
MessageBox.Show("保存成功");
// ischange = false;
}
}
I have a Java Script dynamically creating rows in a table when a contact is added. Each contact added I want to submit them to a cell in a sql database. I have no issues submitting the first contact but i need to use a loop (maybe a for loop?) to submit all of the contacts added to the dynamically created rows in the table. I am very new to the C# community and looking for a little help on how to do this.
When the rows are created via Java Script I also have it creating an input with a 'name' value, this name value is what is used to submit to the cell in the database.
Thanks in advance
Code is below:
JavaScript
function flNames() {
var rowID = parseInt(document.getElementById("ContactsRowCount").value, 10);
rowID++;
if (currentRow > 0) {
saveEdits();
} else {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var sHtml = "<tr id='row" + rowID + "'>" +
"<td class='tblStyle68wlb' id=\"FirstN" + rowID + "\">" + firstName + "</td><input type=\"hidden\" value=\"" + firstName + "\" name=\"cFirst\" />" +
"<td class='tblStyle68wl' id=\"LastN" + rowID + "\">" + lastName + "</td><input type=\"hidden\" value=\"" + lastName + "\" name=\"cLast\" />" +
"<td class='tblStyle68wl' ><button type='button' class='XsmallButtons' onclick='editRow(" + rowID + ")'>Edit</button></td>" +
"<td class='tblStyle68wlb' ><button type='button' class='XsmallButtons' onclick='deleteRow(" + rowID + ")'>Delete</button></td>" +
"</tr>";
$("#dynamicTableTesting").append(sHtml);
newRow++;
document.getElementById("ContactsRowCount").value = rowID;
$("#firstName, #lastName").val("");
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
GetFormData();
}
private void GetFormData()
{
string dynamicFirstName = Request.Form["cFirst"];
string dynamicLastName = Request.Form["cLast"];
string tableContactID = Request.Form[""];
string sql = #"
INSERT INTO
tableContactData
(
fName
,lName
)
VALUES
(
#cFirst
,#cLast
);
SELECT SCOPE_IDENTITY();
";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("cFirst", dynamicFirstName);
cmd.Parameters.AddWithValue("cLast", dynamicLastName);
conn.Open();
tableContactID = cmd.ExecuteScalar().ToString();
conn.Close();
}
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
}
}