Save changes of textbox.text using entity in .net forms - c#

So I'm trying to update a row in a database using the text from a textbox using .net forms.
On pageload I load the value and assign it to the text property of the textbox. Next I allow the user to change the text and click a button to upload, however the value in the database is not changed.
If I change the holter.companyName value to a static string the database updates. Also if I do not assign a companyNameTB.text value at pageloads the update button works as expected.
Any ideas?
protected void Page_Load(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
protected void Button1_Click(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
holter.CompanyName = CompanyNameTB.Text;
holter.Id = 1;
db.SaveChanges();
}

It looks like the Page_Load method is overwriting the textbox when the form is submitted. Put it inside of a conditional statement in order to check to see if the request is a post back, like so:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
}
This should allow the textbox to be populated from the database when the page is initially loaded, but then when the user submits the form that section of code should be skipped so that the new value in the textbox doesn't get overwritten.

Do this in the Page_Load method, otherwise the value in the textBox is refreshed to the original one at any page request (so the post back request too)
if(!Page.IsPostBack)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
And you don't need this line is the Button1_Click method
holter.Id = 1;

Related

How to use Data Binding Linq to SQL to add custom fields

I am developing a windows forms application. I use DataGridView and data binding with LINQ to SQL. It's working. It binds the whole data.
I need some fields instead of whole table data, for example:
The Customers table contains five fields (name, address, mobile, email, age).
I use the code below to get whole data.
private void AssignLocation_Load(object sender, EventArgs e)
{
// Get Datacontext object to connect with data source
SmartxBillingSystemDataContext dc = new SmartxBillingSystemDataContext();
// create table object
Customer customer = new Customer();
var allcustomers = from c in dc.GetTable<Customer>() select c;
// bind to datagrid
customerBindingSource.DataSource = allcustomers;
// now assign binding source to data grid view
dataGridView1.DataSource = customerBindingSource;
}
Now I just need some fields, e.g. Name and Address.
Additionally, I need to add a button in each row like so:
| A Name | An Address | Button |
| Another Name | Fake Address | Button |
How can I achieve this? Please help.
For click event I use below code
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
popUpLocationWindow();
}
private void popUpLocationWindow()
{
MessageBox.Show("I am clicked");
}
But this code not works.
You can create your own class:
public class MyCustomer
{
public string Name { get; set; }
public string Address { get; set; }
}
and select like this:
var allMycustomers = from c in dc.GetTable<Customer>() select new MyCustomer { Name = c.Name, Address = c.Address };
customerBindingSource.DataSource = allMycustomers;
for button:
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.HeaderText = "Button";
btn.Text = "Click Me!";
btn.Name = "btn";
dataGridView1.Columns.Add(btn);
btn.UseColumnTextForButtonValue = true;
Update for button click event you can use dataGridView1_CellClick event..
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 2)
{
MessageBox.Show((e.RowIndex+1) + " Row " + (e.ColumnIndex+1) + " Column button clicked ");
}
}

how to bind database field to a drop downs?

i'm requesting data from database through a D A L file. I want to data bind and show a drop down menu's single option selected against that of the database. How should i do it?
here's my code:
Pages pg = new Pages();
public static string pgId;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Bind_ddlParentPage();
Bind_ddlPageModel();
Bind_ddlArticleModel();
if (!IsPostBack)
{
pgId = Request.QueryString["pageId"];
if (pgId != null)
{
GetData();
}
}
}
}
public void GetData()
{
ddlParentPage.SelectedValue = pg.ParentPage;
//Bind_ddlParentPage();---dropdownlist which is causing problem.
//I want to set this data:: pg.ParentPage to dropdownlist in another
page
ddlPageModel.SelectedValue = pg.PageModel;
//Bind_ddlPageModel();
//All the three drop downs have same table for the source,
'Pages' table and this page is the same page for adding new entry to
Pages table.
ddlArticleModel.SelectedValue = pg.ArticleModel;
//Bind_ddlArticleModel();
}
First, you have a duplication in your conditional statement:
if(!IsPostBack) {
...
if(!IsPostBack) {
...
}
}
Second, you need to bind the data to the dropdown, then set the selected value. Refer: this post
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}

Populating textBoxes with

I'm designing a CheckOut page and I want to automatically load the signed in user's information with data from the database using linq. I'm using a method FillPage which I call in PageLoad and so far it looks like this:
void FillPage(int id)
{
using (DatabaseContext db=new DatabaseContext()
{
var query = (from user in db.[tblUser]
where user.ID == id
select user
).First();
if (query != null)
{
txtName.Text = query.Username;
txtEmail.Text = query.Email;
txtAddress.Text = query.PostalAddress;
ddProvice.SelectedValue = query.Province;
lblPassword.Text = query.Password;
lblDate.Text = query.DateRegistered.ToString();
}
}
}
Why does nothing happen when I load the page?
You must insert more of your code .your problem is not clear
May be in your load event of your page you forget to add
If (! IsPostback)
{
}
And may be you have reset your fields
public void MyPage_load( object sender , EventArgs e)
{
//Reset fields
}
This will fix your problem
public void MyPage_load( object sender , EventArgs e)
{
If (! IsPostback)
{
//Reset fields
}
}

Passing data to another page for bookmarking function

I have 1 gridview look like this:
Anytime user click on Bookmark button, I want to send the data in ProgramID column of that row to the List and pass it to second gridview in another page.But my second gridview doesn't display any data. What am I doing wrong?
This is my code for Bookmark button:
protected void btnSelect_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
GridViewRow row = (GridViewRow)b.NamingContainer;
var ProgramID = row.FindControl("lblProgramID") as Label;
string stringProgramID = ProgramID.Text;
List<string> bookmarkPrograms = new List<string>();
bookmarkPrograms.Add(stringProgramID);
Session["BookmarkProgram"] = bookmarkPrograms;
}
And here is the code in Bookmark page:
protected void Page_Load(object sender, EventArgs e)
{
List<string> bookMarkPrograms = (List<string>)Session["BookMarkPrograms"];
GridView1.DataSource = bookMarkPrograms;
GridView1.DataBind();
}

C# view data in form linked with foreign key

I have a local database (SQL) with two tables Contact and Address. The Contact table contains 5 address fields (Address1, Address2,...) that are foreign keys linked to the primary key of the Address table. What ik want to do is when I select (for instance using a combobox) a contacts name, view all addresses linked to the contact. I'm a complete noob in C# programming and have no idee to make the above happen. Can anyone show me how I can view the addresses by selecting the contacts name?
EDIT (after trying some coding):
Ok, this is how far I get. I have my two forms. FORM 1 has a datagridview, viewing a button, firstname and lastname. Entering firstname and lastname in textBox1 and textBox2 and pressing button1 results in a list of records that match firstname OR lastname.
Clicking the button in column 0 shows the contactsheet. I've tried to pass firstname and lastname to textboxes tboFNAME and tboLNAME, but nothing appears in these textboxes.
In the next stage I would like to pass the address ID's (foreign keys) to the contactsheet and subsequently load the linked data in the corresponding textboxes.
FORM 1:
public partial class Form1 : Form
{
//SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
dataGridView1.Visible = true;
int varCount;
varCount = 0;
int i = 0;
for (i = 1 ; i < dataGridView1.Rows.Count-1; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
if (dataGridView1[3, i].Value.ToString() == textBox1.Text
|| dataGridView1[5, i].Value.ToString() == textBox2.Text
)
{
dataGridView1.Rows[i].Visible = true;
varCount += 1;
Console.WriteLine(varCount);
int RHeight = dataGridView1.RowTemplate.Height;
int gridHeight = (varCount * RHeight) + RHeight;
dataGridView1.Height = gridHeight;
}
else
{
dataGridView1.Rows[i].Visible = false;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sAFIREDBDataSet1.contactdata' table. You can move, or remove it, as needed.
this.contactdataTableAdapter1.Fill(this.sAFIREDBDataSet1.contactdata);
this.contactdataTableAdapter.Fill(this.sAFIREDBDataSet.contactdata);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
String fnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[3].Value;
String lnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[5].Value;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
Contactsheet myForm = new Contactsheet();
myForm.getFNAME = fnameRef;
myForm.getLNAME = lnameRef;
myForm.Show();
}
}
}
FORM 2 (Contactsheet)
public partial class Contactsheet : Form
{
public Contactsheet()
{
InitializeComponent();
}
public string getFNAME;
public string getLNAME;
private void Contactsheet_Load(object sender, EventArgs e)
{
tboFNAME.Text = getFNAME;
tboLNAME.Text = getLNAME;
}
}
First of all you must connect to your SQL db as you probably know.
I think that the simplest way will be to use Entity Framework (version 5 or 6).
Create new edmx file, new connection to your database and import your tables.
Try to write some code. May be you figured it out. If not then ask more accurate question with examples of your tries:)

Categories