Dynamic text boxes - c#

I'm accessing record from my database .. and generating dynamic text boxes to number of records fetch..
Then I'm assigning text to these text boxes from the dataset ..
I'm doing this all on the Change event of combo box .. But when I change the event .. that is change value in combo box the value still remain the same in text boxes i.e fetch from previous event ...
The values in text boxes do not update.
Here is my code
private void ComBoSem_SelectedIndexChanged(object sender, EventArgs e)
{
semID();
conct.MyConnection();
try
{
SqlCommand SubjectsCMD = new SqlCommand("select SubjectName from Subjects where Sem_ID= '" + semesterID + "'", Connectioncs.con);
SqlDataAdapter SubjectDA = new SqlDataAdapter();
conct.openCon();
SubjectDA.SelectCommand = SubjectsCMD;
SubjectsCMD.ExecuteNonQuery();
subjectDS.Clear();
SubjectDA.Fill(subjectDS, "sub");
if (subjectDS.Tables["sub"].Rows.Count > 0)
{
TextBox[] txtsubject = new TextBox[subjectDS.Tables["sub"].Rows.Count];
DateTimePicker[] DtPker = new DateTimePicker[subjectDS.Tables["sub"].Rows.Count];
Label lblSubjectName = new Label();
lblSubjectName.Text = "Subjects Name";
lblSubjectName.Location = new Point(60, 115);
GB_DateSHeet.Controls.Add(lblSubjectName);
Label lblPaperTime = new Label();
lblPaperTime.Text = "Subjects Name";
lblPaperTime.Location = new Point(300, 115);
GB_DateSHeet.Controls.Add(lblPaperTime);
////// label Control Finished here
for (int i = 0; i < subjectDS.Tables["sub"].Rows.Count; i++)
{
//// dynamic Textboxes
txtsubject[i] = new TextBox();
Point p = new Point(50, 143 + (i * 28));
txtsubject[i].Size = new Size(168, 21);
txtsubject[i].Location = p;
DtPker[i] = new DateTimePicker();
DtPker[i].Location = new Point(300, 143 + (i * 28));
txtsubject[i].Text = subjectDS.Tables["sub"].Rows[i]["SubjectName"].ToString();
}
conct.openCon();
// adding controls to GridView
for (int i = 0; i < subjectDS.Tables["sub"].Rows.Count; i++)
{
GB_DateSHeet.Controls.Add(txtsubject[i]);
GB_DateSHeet.Controls.Add(DtPker[i]);
}
}
else
{
MessageBox.Show("No Record Found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

Dynamically Created TextBox AutoPostBack on TextChanged but Event Function is not called

everybody,
I have been trying for days now to solve this problem with no success.
I have textboxes in table cells which are created dynamically upon button click. Three of these buttons will take a value, calculation method (% or Const Value) and the value to apply respectively. Below is the function which creates these TB's among other controls.
protected void btnAddService_Click(object sender, EventArgs e)
{
TableRow r = new TableRow();
TableCell c0 = new TableCell();
TableCell c1 = new TableCell();
TableCell c2 = new TableCell();
TableCell c3 = new TableCell();
TableCell c4 = new TableCell();
TableCell c5 = new TableCell(); // Management Fees (% or Const)
TableCell c6 = new TableCell(); // Management Fees Value
TableCell c7 = new TableCell(); // Remarks
service s = new service();
if (serCount == 0)
{
tblHeader.Visible = true;
}
// Add the Services DropDownList...
DropDownList ddlS = new DropDownList();
ddlS.ID = "ddlServices" + serCount;
ddlS.Items.Add("Management");
ddlS.Items.Add("MEP");
ddlS.Items.Add("Landscaping");
ddlS.Items.Add("Pest Control");
ddlServices.Add(ddlS);
ddlS.CssClass = "form-control";
ddlS.Width = Unit.Percentage(100);
c0.Controls.Add(ddlS);
c0.Width = Unit.Percentage(15);
s.serviceName = "Management";
// Add Subcontracted Checkbox...
CheckBox chkSubCont = new CheckBox();
chkSubCont.ID = "chkSubCont" + serCount;
chkSubContracted.Add(chkSubCont);
c1.Controls.Add(chkSubCont);
c1.Width = Unit.Percentage(5);
c1.HorizontalAlign = HorizontalAlign.Center;
s.subcontracted = false;
// Add Subcontracted Value...
TextBox txtSubContVal = new TextBox();
txtSubContVal.ID = "txtSubcontractVal" + serCount;
txtSubContVal.CssClass = "form-control";
txtSubContVal.Attributes.Add("placeholder", "0.000");
txtSubContVal.Style.Add("text-align", "right");
txtSubcontValue.Add(txtSubContVal);
c2.Controls.Add(txtSubContVal);
c2.Width = Unit.Percentage(10);
s.subcontValue = 0;
// Add Management Fees Type (% or Const)...
DropDownList ddlMFT = new DropDownList();
ddlMFT.Items.Add("%");
ddlMFT.Items.Add("Value");
ddlMFT.CssClass = "form-control";
ddlMFT.Width = Unit.Percentage(100);
ddlMFT.ID = "ddlManFeesType" + serCount;
ddlManFeesType.Add(ddlMFT);
c5.Controls.Add(ddlMFT);
c5.Width = Unit.Percentage(5);
// Add Management Fees Value...
TextBox txtMFVal = new TextBox();
txtMFVal.CssClass = "form-control";
txtMFVal.Attributes.Add("placeholder", "0.000");
txtMFVal.Style.Add("text-align", "right");
txtMFVal.Width = Unit.Percentage(100);
// txtMFVal.ID = "txtManFeesValue" + serCount;
txtMFVal.AutoPostBack = true;
txtMFVal.TextChanged += new EventHandler(txtManFeesVal_TextChange);
txtManFeesValue.Add(txtMFVal);
c6.Controls.Add(txtMFVal);
c6.Width = Unit.Percentage(10);
// Add Manpower Value...
TextBox txtManp = new TextBox();
txtManp.ID = "txtManpower" + serCount;
txtManp.CssClass = "form-control";
txtManp.Attributes.Add("placeholder", "0");
txtManp.Style.Add("text-align", "center");
txtManPower.Add(txtManp);
c3.Controls.Add(txtManp);
c3.Width = Unit.Percentage(10);
s.manPower = 0;
// Add Quoted Value...
TextBox txtQuotVal = new TextBox();
txtQuotVal.ID = "txtQuotedValue" + serCount;
txtQuotVal.CssClass += "form-control";
// txtQuotVal.Text = "0.000";
txtQuotVal.Attributes.Add("placeholder", "0.000");
txtQuotVal.Style.Add("text-align", "right");
txtQuotVal.AutoPostBack = true;
txtQuotVal.ClientIDMode = ClientIDMode.Static;
txtQuotVal.TextChanged += (o, ep) => {
TextBox t = sender as TextBox;
if (t.Text == "")
{
t.Text = "0.000";
}
txtPrjValue.Text = (int.Parse(txtPrjValue.Text) + int.Parse(t.Text)).ToString();
};
txtQuotValue.Add(txtQuotVal);
c4.Controls.Add(txtQuotVal);
c4.Width = Unit.Percentage(10);
// Add Remarks Box...
TextBox txtRem = new TextBox();
txtRem.ID = "txtRemarks" + serCount;
txtRem.CssClass += "form-control";
txtRem.ClientIDMode = ClientIDMode.Static;
txtRem.Width = Unit.Percentage(100);
txtRemarks.Add(txtRem);
c7.Controls.Add(txtRem);
c7.Width = Unit.Percentage(35);
s.quotedValue = 0;
// Add the cells to the new row...
r.Cells.Add(c0);
r.Cells.Add(c1);
r.Cells.Add(c2);
r.Cells.Add(c5);
r.Cells.Add(c6);
r.Cells.Add(c3);
r.Cells.Add(c4);
r.Cells.Add(c7);
// Add the new row...
tblServices.Rows.Add(r);
serCount++;
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
Upon TextChanged of txtMFVal text, it does PostBack but it doesn't call the attached event handler, shown below:
protected void txtManFeesVal_TextChange(object sender, EventArgs e)
{
TextBox txtMFV = sender as TextBox;
// Get the parent cell of the TextBox...
TableRow tr = txtMFV.Parent.Parent as TableRow;
TextBox txtSCV = tr.Cells[2].Controls[0] as TextBox;
TextBox txtMFT = tr.Cells[5].Controls[0] as TextBox;
double scv = Double.Parse(txtSCV.Text);
double mfv = Double.Parse(txtMFV.Text);
double v = 0;
if (txtMFT.Text == "%")
{
v = (scv * mfv) / 100;
}
else
{
v = scv + mfv;
}
TextBox txtQP = tr.Cells[6].Controls[0] as TextBox;
txtQP.Text = v.ToString();
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
I have tried so many tricks I have found on the net and all didn't work.
Please, help.
Thanks,

How to save multiple dynamic textboxes value into SQL Server database

I want to add some panel dynamically into a single panel on a button click. And each dynamic panel consist of multiple text box in horizontally. And then I want to save those text box value into the database.
I have completed to add dynamic panel and horizontal multiple text box into that panel. But couldn't know how to save them into database.
Here is the code I have written:
int v = 0;
TextBox txt1;
TextBox txt2;
TextBox txt3;
TextBox txt4;
TextBox txt5;
ComboBox cmb4;
public void tett()
{
v = 0;
Panel whitePanel = new Panel();
whitePanel.Name = "wt";
// Quantity
txt1 = new TextBox();
txt1.Location = new Point(192, 38);
txt1.Size = new Size(120, 24);
txt1.Name = "text" + v ;
txt1.Text = txt1.Name;
v = v + 1;
// Total Price
txt2 = new TextBox();
txt2.Location = new Point(566, 38);
txt2.Size = new Size(120, 24);
txt2.Name = "text" + v;
txt2.Text = txt2.Name;
txt2.TextChanged += Txt2_TextChanged;
v = v + 1;
// Unit Price
txt3 = new TextBox();
txt3.Location = new Point(753, 38);
txt3.Size = new Size(120, 24);
txt3.Name = "text" + v;
txt3.Text = txt3.Name;
v = v + 1;
// Sell Price
txt4 = new TextBox();
txt4.Location = new Point(903, 38);
txt4.Size = new Size(120, 24);
txt4.Name = "text" + v;
txt4.Text = txt4.Name;
v = v + 1;
// Product
txt5 = new TextBox();
txt5.Location = new Point(5, 38);
txt5.Size = new Size(120, 24);
txt5.Name = "text" + v;
txt5.Text = txt5.Name;
txt5.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt5.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt5.MouseClick += textBox5_MouseClick;
Label lbl3 = new Label();
Label lbl4 = new Label();
Label lbl5 = new Label();
Label lbl6 = new Label();
Label lbl7 = new Label();
Label lbl8 = new Label();
lbl3.Location = new Point(5, 15);
lbl3.Text = "Product";
lbl4.Location = new Point(192, 15);
lbl4.Text = "Quantity";
lbl5.Location = new Point(379, 15);
lbl5.Text = "Unit";
lbl6.Location = new Point(566, 15);
lbl6.Text = "Total Price";
lbl7.Location = new Point(753, 15);
lbl7.Text = "Unit Purchase Price";
lbl8.Location = new Point(903, 15);
lbl8.Text = "Unit Sell Price";
cmb4 = new ComboBox();
// Unit
cmb4.Location = new Point(379, 38);
cmb4.Size = new Size(120, 24);
whitePanel.BackColor = ColorTranslator.FromHtml("#ECF0F5");
whitePanel.Location = new Point(1, a * 10);
whitePanel.Size = new Size(1330, 60);
var _button = new Button();
_button.Text = "Dispose";
_button.Name = "DisposeButton";
_button.Location = new Point(1053, 38);
_button.MouseClick += _button_MouseClick;
whitePanel.Controls.Add(_button);
a = a + 5;
v = v + 1;
whitePanel.Controls.Add(lbl3);
whitePanel.Controls.Add(lbl4);
whitePanel.Controls.Add(lbl5);
whitePanel.Controls.Add(lbl6);
whitePanel.Controls.Add(lbl7);
whitePanel.Controls.Add(lbl8);
whitePanel.Controls.Add(txt1);
whitePanel.Controls.Add(txt2);
whitePanel.Controls.Add(txt3);
whitePanel.Controls.Add(txt4);
whitePanel.Controls.Add(txt5);
whitePanel.Controls.Add(cmb4);
panel1.Controls.Add(whitePanel);
}
In this way the output is like this..... By click on the New Purchase this multiple panel with text box will appear:
Multiple dynamic panel with multiple text box
Here the way of setting text box name is not seems better way to me. I want to use an array for set the name of text boxes.
And after all I want to save those values into db by click on the save button using an array or for loop... But I don't know how to define it..
Can anyone please help me?
And thanks in advance
With this approach, a gridview is usefull.
But within your question, the approach is;
int rowNum = 1;
public void tett() {
Control[] controlsToAdd = { new TextBox(), new TextBox(), new ComboBox(), new TextBox(), new TextBox(), new TextBox(), new Button() };
string[] labels = { "Product", "Quantity", "Unit", "Total Price", "Unit Purchase", "Unit Sell Price" };
Panel whitePanel = new Panel() {
Name = "wt",
Dock = DockStyle.Top,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
AutoSize = true,
Padding = new Padding(0, 5, 0, 5),
BackColor = ColorTranslator.FromHtml("#ECF0F5")
};
int controlX = 5, controlY = 15, controlDistance = 15;
for (int i = 0; i < controlsToAdd.Length; i++) {
if (labels.Length > i) {
var label = new Label() {
Text = labels[i],
Location = new Point(controlX, controlY)
};
whitePanel.Controls.Add(label);
}
var control = controlsToAdd[i];
control.Location = new Point(controlX, controlY + 23);
control.Size = new Size(120, 24);
if (control is Button) {
control.Name = "disposeButton" + i;
control.Text = "Dispose";
control.Click += _button_MouseClick;
} else {
if(i == 0) { //if it is the Product textbox
((TextBox)control).AutoCompleteSource = AutoCompleteSource.CustomSource;
((TextBox)control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//control.MouseClick += textBox5_MouseClick;
}
control.Name = "Text" + i;
control.Text = "Row" + rowNum + " Text" + i;
}
whitePanel.Controls.Add(control);
controlX += 120 + controlDistance;
}
panel1.Controls.Add(whitePanel);
whitePanel.BringToFront();
rowNum++;
}
private void _button_MouseClick(object sender, EventArgs e) {
//button does its job here
((Button)sender).Parent.Parent.Controls.Remove(((Button)sender).Parent);
}
public SqlConnection Conn { get; }
void save() {
foreach(Panel whitePanel in panel1.Controls) {
var sqlString = "INSERT INTO products(productField, quantityField, unitField, priceField, purchaseField, sellPriceField) VALUES (";
foreach (Control control in whitePanel.Controls) {
if(!(control is Label) && !(control is Button)) { //So, textbox or combobox remained
sqlString += "'"+ control.Text +"', ";
}
}
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ")";
//Assume you have previous construction of SqlConnection as name "Conn"
if (Conn != null) {
if (Conn.State != ConnectionState.Open) Conn.Open();
using (var cmd = new SqlCommand(sqlString, Conn)) {
cmd.ExecuteNonQuery();
}
Conn.Close();
}
Console.WriteLine(sqlString);
}
}
I have tested and works as expected. If it is not suit your needs, make me know.

How to add rows to a RadGridView in WinForms using c#

I am trying to add a rows to a RadGridView when a use click a button on the form (ie. "Add".)
When the form load I add columns to the RadGridView and make all of them all ReadOnly except one .
When a user click the "Add" button, I want to add a row to this RadGridView. Basically, a user types a UPC code, then I read data from the database and add new row in a grid view with the item name, item price.
Here is what I did to create the columns
private void Register_Load(object sender, EventArgs e) {
GridViewTextBoxColumn UPC = new GridViewTextBoxColumn();
UPC.Name = "UPC";
UPC.HeaderText = "UPC";
UPC.FieldName = "UPC";
UPC.MaxLength = 50;
UPC.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(UPC);
radGridView1.Columns["UPC"].Width = 120;
radGridView1.Columns["UPC"].ReadOnly = true;
GridViewTextBoxColumn ItemName = new GridViewTextBoxColumn();
ItemName.Name = "Item Name";
ItemName.HeaderText = "Item Name";
ItemName.FieldName = "ItemName";
ItemName.MaxLength = 100;
ItemName.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(ItemName);
radGridView1.Columns["Item Name"].Width = 210;
radGridView1.Columns["Item Name"].ReadOnly = true;
GridViewDecimalColumn QtyColumn = new GridViewDecimalColumn();
QtyColumn.Name = "Qty";
QtyColumn.HeaderText = "Quantity";
QtyColumn.FieldName = "Qty";
QtyColumn.DecimalPlaces = 1;
radGridView1.MasterTemplate.Columns.Add(QtyColumn);
radGridView1.Columns["Qty"].Width = 75;
GridViewMaskBoxColumn PriceColumn = new GridViewMaskBoxColumn();
PriceColumn.Name = "Unit Price";
PriceColumn.FieldName = "UnitPrice";
PriceColumn.HeaderText = "Unit Price";
PriceColumn.MaskType = MaskType.Numeric;
PriceColumn.Mask = "C";
PriceColumn.TextAlignment = ContentAlignment.BottomRight;
PriceColumn.FormatString = "{0:C}";
PriceColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(PriceColumn);
radGridView1.Columns["Unit Price"].Width = 75;
radGridView1.Columns["Unit Price"].ReadOnly = true;
GridViewMaskBoxColumn TotalColumn = new GridViewMaskBoxColumn();
TotalColumn.Name = "Total Price";
TotalColumn.FieldName = "TotalPrice";
TotalColumn.HeaderText = "Total Price";
TotalColumn.MaskType = MaskType.Numeric;
TotalColumn.Mask = "C";
TotalColumn.TextAlignment = ContentAlignment.BottomRight;
TotalColumn.FormatString = "{0:C}";
TotalColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(TotalColumn);
radGridView1.Columns["Total Price"].Width = 75;
radGridView1.Columns["Total Price"].ReadOnly = true;
}
To add the row Here is what I am doing "when a user click the 'Add' button)
private void ButtonAdd_Click(object sender, EventArgs e) {
string UPC = InputUPC.Text.Trim();
if (UPC.Length < 3) {
return;
}
string sql = " SELECT p.productName, p.price "
+ " FROM products AS p "
+ " WHERE p.productUPC = #upc ";
var parms = new List<MySqlParameter>();
parms.Add(new MySqlParameter("#upc", UPC));
var db = new dbConnetion();
foreach (var i in db.getData(sql, parms, r =>
new ProductsTable() {
_productName = r["productName"].ToString(),
_price = Convert.ToDouble(r["price"])
}
)
) {
//radGridView1.Rows[0].Cells[0].Value = 4.3;
radGridView1.Rows[0].Cells["UPC"].Value = UPC;
radGridView1.Rows[0].Cells["Item Name"].Value = i._productName;
radGridView1.Rows[0].Cells["Qty"].Value = "1";
radGridView1.Rows[0].Cells["Unit Price"].Value = i._price;
radGridView1.Rows[0].Cells["Total Price"].Value = (Convert.ToDouble(i._price) * Convert.ToInt32(radGridView1.Rows[0].Cells["Qty"].Value)).ToString();
}
}
But the add row is giving me an error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How can I correctly add rows to the RadGridView when the "Add" button is clicked.
ButtonAdd_Click is wrong because the foreach is always trying to set row 0, which doesn't exist.
You don't specify what GridView you are using, so I can't give specifics, but typically you should be able to call Rows.Add(...).

How To update Text box contents after a selection change in ListPicker in windows phone 7?

I have to update my txtid , txtName ,txtAge ,txtContact..OnSelectionChange of ListPicker , but even after selecting items it is not updating txtfields . How can i step up on it ?
public partial class Update : PhoneApplicationPage
{
Button btnUpdate1 = null;
TextBox txtid = null;
TextBox txtName = null;
TextBox txtAge = null;
TextBox txtContact = null;
ListPicker lp = null;
int selectedItem ;
public Update()
{
InitializeComponent();
int x = noofrows();
createUpdateButton();
createListPicker();
selectedItem = Convert.ToInt32(lp.SelectedItem);
createTxtId(selectedItem);
createTxtName(selectedItem);
createTxtAge(selectedItem);
createTxtContact(selectedItem);
}
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
};
LayoutRoot.Children.Add(lp);
}
public void createUpdateButton()
{
btnUpdate1 = new Button();
btnUpdate1.Margin = new Thickness(100, 600, 0, 0);
btnUpdate1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btnUpdate1.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
btnUpdate1.Height = 100;
btnUpdate1.Width = 150;
btnUpdate1.Content = "update";
btnUpdate1.Foreground = new SolidColorBrush(Colors.White);
btnUpdate1.Background = new SolidColorBrush(Colors.Black);
btnUpdate1.BorderBrush = new SolidColorBrush(Colors.White);
btnUpdate1.BorderThickness = new Thickness(3);
btnUpdate1.FontSize = 28;
LayoutRoot.Children.Add(btnUpdate1);
btnUpdate1.Click += (s, e) =>
{
UpdateDatabase(selectedItem);
};
}
public void createTxtId(int z)
{
int id = z ;
txtid = new TextBox();
txtid.Margin = new Thickness(12, 100, 0, 0);
txtid.Width = 400;
txtid.Height = 100;
txtid.FontSize = 28;
txtid.Foreground = new SolidColorBrush(Colors.Black);
txtid.BorderBrush = new SolidColorBrush(Colors.Black);
txtid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtid.BorderThickness = new Thickness(3);
txtid.IsReadOnly = true;
txtid.Text = " " + id;
LayoutRoot.Children.Add(txtid);
}
public void createTxtName(int z)
{
txtName = new TextBox();
txtName.Margin = new Thickness(12, 200, 0, 0);
txtName.Width = 400;
txtName.Height = 100;
txtName.FontSize = 28;
txtName.Foreground = new SolidColorBrush(Colors.Black);
txtName.BorderBrush = new SolidColorBrush(Colors.Black);
txtName.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtName.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtName.BorderThickness = new Thickness(3);
txtName.Text = SelectName(z);
txtName.Tap += (s, e) =>
{
if (txtName.Text == "Name")
{
txtName.Text = "";
}
};
txtName.LostFocus += (s, e) =>
{
if (txtName.Text == "")
{
txtName.Text = "Name";
}
};
LayoutRoot.Children.Add(txtName);
}
public void createTxtAge(int z)
{
txtAge = new TextBox();
txtAge.Margin = new Thickness(12, 300, 0, 0);
txtAge.Width = 400;
txtAge.Height = 100;
txtAge.FontSize = 28;
txtAge.Foreground = new SolidColorBrush(Colors.Black);
txtAge.BorderBrush = new SolidColorBrush(Colors.Black);
txtAge.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtAge.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtAge.BorderThickness = new Thickness(3);
txtAge.MaxLength = 2;
txtAge.Text = SelectAge(z);
txtAge.InputScope = new InputScope();
txtAge.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtAge.Tap += (s, e) =>
{
if (txtAge.Text == "Age")
{
txtAge.Text = "";
}
};
txtAge.LostFocus += (s, e) =>
{
if (txtAge.Text == "")
{
txtAge.Text = "Age";
}
};
LayoutRoot.Children.Add(txtAge);
}
public void createTxtContact(int z)
{
txtContact = new TextBox();
txtContact.Margin = new Thickness(12, 400, 0, 0);
txtContact.Width = 400;
txtContact.Height = 100;
txtContact.FontSize = 28;
txtContact.MaxLength = 10;
txtContact.Foreground = new SolidColorBrush(Colors.Black);
txtContact.BorderBrush = new SolidColorBrush(Colors.Black);
txtContact.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtContact.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtContact.BorderThickness = new Thickness(3);
txtContact.Text = SelectContact(z);
txtContact.InputScope = new InputScope();
txtContact.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtContact.Tap += (s, e) =>
{
if (txtContact.Text == "Contact")
{
txtContact.Text = "";
}
};
txtContact.LostFocus += (s, e) =>
{
if (txtContact.Text == "")
{
txtContact.Text = "Contact";
}
};
LayoutRoot.Children.Add(txtContact);
}
public Int32 noofrows()
{
int b = Convert.ToInt32((Application.Current as App).db.SelectList("select count(*) from details"));
return b;
}
public string returnID(int z)
{
return Convert.ToString((Application.Current as App).db.SelectList("select id from details where id =" + z));
}
public String SelectName(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select name from details where id =" + x));
}
public String SelectAge(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select age from details where id =" + x));
}
public String SelectContact(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select contact from details where id =" + x));
}
public void UpdateDatabase(int ID)
{
if (txtName.Text=="Name")
{
MessageBox.Show("Enter a valid Name");
}
else if (txtAge.Text.Length>=3||txtAge.Text=="Age")
{
MessageBox.Show("Enter A valid Age (1-99)");
}
else if (txtContact.Text.Length != 10)
{
MessageBox.Show("Enter a valid Mobile number Of 10 digit");
}
else
{
string s1 = "update details set id='" + Convert.ToInt64(txtid.Text) + "', name = '" + txtName.Text + "', age = '" + txtAge.Text + "', contact = '" + txtContact.Text + "'where id = " + ID;
string s2 = Convert.ToString((Application.Current as App).db.SelectList(s1));
MessageBox.Show("Updated Successfully");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
You are using so much code. Its would be better if you follow the MVM architecture and try to set Bind the textblocks to your viewModel. Lets consider the following scenario.
You have binded the xaml elements to selectedItem in your viewModel. Now when selectedItem's value is changed Notify event is triggered which will notify the UI and the values will automatically be updated.
I recommend you to study viewmodel and try to implement it. Its really easy and would save you a lot of hassle.
Try implementing some samples
Hope it helps :)
I got this ...
Actually if we want to update that we need to change text of each text box . So after the selection change , Try it like this.
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
txtid.Text = selectedItem.ToString();
txtName.Text = SelectName(selectedItem);
txtAge.Text = SelectAge(selectedItem);
txtContact.Text = SelectContact(selectedItem);
};
LayoutRoot.Children.Add(lp);
}
This will update Immediately after Every selection change Event .

Bind DataGridviewComboBoxCell into DataGridViw

I have to bind each cell of rows with different data like.
ProductID Color(DataGridviewComboBoxColumn)
1 Red - (ComboboxCell having value only Red,Black,Green and Red is Selected)
....
4 Yellow- (ComboboxCell having value only Yellow,Gold and Yellow is Selected)
When I bind Items of cell and debug it will show Items in DataGridviewComboBoxCell but when going to run application it will display blank on select Combobox.
What can i do for this?
Form Design
private void InitializeComponent()
{
this.dataGridView2 = new System.Windows.Forms.DataGridView();
this.ProductId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Color = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.ColorIds = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit();
this.SuspendLayout();
//
// dataGridView2
//
this.dataGridView2.AllowUserToAddRows = false;
this.dataGridView2.AllowUserToDeleteRows = false;
this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView2.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ProductId,
this.Color,
this.ColorIds});
this.dataGridView2.Location = new System.Drawing.Point(12, 12);
this.dataGridView2.Name = "dataGridView2";
this.dataGridView2.Size = new System.Drawing.Size(704, 312);
this.dataGridView2.TabIndex = 1;
//
// ProductId
//
this.ProductId.DataPropertyName = "ProductId";
this.ProductId.HeaderText = "ProductId";
this.ProductId.Name = "ProductId";
//
// Color
//
this.Color.HeaderText = "Color";
this.Color.Name = "Color";
this.Color.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.Color.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
// ColorIds
//
this.ColorIds.DataPropertyName = "ColorIds";
this.ColorIds.HeaderText = "ColorIds";
this.ColorIds.Name = "ColorIds";
this.ColorIds.Visible = false;
}
Code :
dataGridView2.AutoGenerateColumns = false;
DataTable dt = //data from Product Table
dataGridView2.DataSource = dt;
DataTable dtColors = //data from Color Table
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
String ColorIds = dataGridView2.Rows[i].Cells["ColorIds"].Value.ToString();
DataTable dtfiltered = dtColors.Select("ColorId IN (" + ColorIds + ")").CopyToDataTable();
DataGridViewComboBoxCell col = (DataGridViewComboBoxCell)dataGridView2.Rows[i].Cells["Color"];
col.Items.Clear();
foreach (DataRow dr in dtfiltered.Rows)
{
col.Items.Add(new ComboBoxItem(dr["ColorId"].ToString(), dr["Color"].ToString()));
}
col.Value = col.Items[0];
}

Categories

Resources