I am a novice programmer (c #) and I stuck. I do not know why the compiler does not see the variable from another void. About a week ago in another program it worked and now does not want to. I was looking for a similar problem but I have not found.
public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
int index;
if (ev.CommandName == "Update")
{
index = Convert.ToInt32(ev.CommandArgument);
}
}
protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
I want the index variable to the SqlCommand object.
By the way. Is this good code? It will be works ? i want to varible 'Permit' insert in to cell [LastModified] after updating data(row) in gridview.
It seems that this not works as it should :( I mean, variable 'index' is fine now, but code is just broken.
Declare your variable outside your void, so you can access it from all members. As you have it it is only visible to Gridcommandevent.
int index;
public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
if (ev.CommandName == "Update")
{
index = Convert.ToInt32(ev.CommandArgument);
}
}
protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
As per Andreas Niedermair suggestion, and since you say you are a novice programmer, you should have a look at this MSDN Article.
Related
Okay so here's my code. Everything works and saves to the database.
Though, it only stores the current value that's displayed in the combobox.
I want it to store all 3 values, for each value has its own checkboxes.
How would I go about coding something that saves each of the 3 values and the corresponding checkboxes to the database(sql)?
Form
, Code
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.Text + "', '" + cboStateOperator.Text + "', '" + cboStateType.Text + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to use "combobox.SelectedItem" or "combobox.SelectedValue". If your combobox is filled with datasource you need to define "DisplayMember" and "ValueMember" for it.
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.SelectedItem+ "', '" + cboStateOperator.SelectedItem+ "', '" + cboStateType.SelectedItem+ "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to get the combo box items for each combo box as shown below and then save it.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder comboBox1Items = new StringBuilder();
foreach (var item in comboBox1.Items)
{
comboBox1Items.Append(item + " ");
}
string cb1Items = comboBox1Items.ToString();
}
I tried Implementing the code for Edit and Update button for gridview but it doesn't seems working for me. Add button working well but delete and update do not working. During runtime error the error is "An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Unknown column 'p001' in 'where clause'"
Note: type of P_Id in the database is varchar(10), name varch(100), level varchar, value varchar
public partial class ManagePractice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
TextBox txtID = (TextBox)GridView1.FooterRow.FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.FooterRow.FindControl("txtSubject");
RadioButtonList Level = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList1");
AddPractice(txtID.Text.Trim(), txtSubject.Text.Trim(), Level.Text.Trim(), PType.Text.Trim());
BindData();
}
private void AddPractice(string P_Id, string subject, string level, string type)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "insert into practice(P_Id,name,level,value) values ('" + P_Id + "','" + subject + "','" + level + "','" + type + "')";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select P_Id,level,name,value from practice", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = (GridView1.DataKeys[e.RowIndex].Value.ToString ());
DeletePractice(id);
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubject");
// TextBox Level1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtlevel");
// TextBox PType1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPType1");
RadioButtonList Level = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
UpdatePractice( txtID.Text , txtSubject.Text, Level.Text, PType.Text);
GridView1.EditIndex = -1;
BindData();
}
private void UpdatePractice( string P_Id, string name, string level, string value)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + " WHERE P_Id=" + P_Id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void DeletePractice(string id)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "DELETE FROM practice WHERE P_Id=" + id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
First sight:
Since P_Id column has VARCHAR(10) datatype, I figured out you forget to include some additional apostrophes on UPDATE & DELETE clause. The correct form of SQL statements should be this (notice additional apostrophe signs around P_Id column):
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + "' WHERE P_Id= '" + P_Id + "'";
and
string query = "DELETE FROM practice WHERE P_Id='" + id + "'";
Only string values require apostrophes around them, numbers do not.
On my main form I have queried the user id on submission. Once I save the id to a variable how can I call it on another windows form in the same application?
This is what I have so far
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.database.windows.net;Initial Catalog=userlogins;Persist Security Info=True;User ID=****;Password=****");
SqlDataAdapter sda = new SqlDataAdapter("Select ID from users where username='" + txtUsername.Text + "' and password='" + txtPassword.Text + "' ", con);
SqlCommand cmd = con.CreateCommand();
con.Open();
// save SQL ID to variable
cmd.CommandText = "Select Id from users where username = '" + txtUsername.Text + "'";
int sqlid = ((int)cmd.ExecuteScalar());
Any information would be appreciated, I really need the ID on multiple other pages!
If you are using the ExecuteScalar() method, it's important to remember that this will only return the contents of the first cell in your results, so it can generally help to use in conjunction with a TOP 1 statement.
Additionally, you should consider refactoring your code to use parameterization, which should help avoid nastiness like SQL Injection and will also help mitigate any syntax issues :
// Build your connection
using(var con = new SqlConnection("your-connection-string"))
{
// Build your query
var query = "SELECT TOP 1 ID FROM users WHERE username = #username AND password = #password";
// Build a command to execute your query
using(var cmd = new SqlCommand(con,query))
{
// Open your connection
con.Open();
// Add your parameters
cmd.Parameters.AddWithValue("#username", txtUsername.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
// Get your ID
var sqlid = Convert.ToInt32(cmd.ExecuteScalar());
// Do something here
}
}
One way to do this is with events:
public class IdChangedEventArgs : EventArgs
{
int ChangedId {get;set;};
}
public delegate void IdChangedEventHandler(object sender, IdChangedEventArgs e);
public event IdChangedEventHandler IdChangedEvent;
private void btnLogin_Click(object sender, EventArgs e)
{
int sqlid = ((int)cmd.ExecuteScalar());
IdChangedEvent(this, new IdChangedEventArgs {ChangedId = sqlid;} );
}
In each of your interested forms, subscribe to the events. When handled, update your GUI however you want.
This question already has answers here:
The multi-part identifier "TextBox1.Text" could not be bound in C# ASP.NET?
(3 answers)
Closed 9 years ago.
I know this is a duplicate to some questions here, but believe me I've tried all of them, and no luck.
I am new to C#+MySQL.
I have a database with 2 tables, programmers and softwares. I have a column in the softwares table named programmersid. It's one to many relation. I have two listboxes. The first one is with the programmers name, and when I click on a programmer, it's showing me the softwares that he has made.
When I click on a software, the text will be put into a textbox, and I have an update button. When I click it, it should update the name of that software.
Here is my code:
public partial class Form1 : Form
{
private DataSet ds;
private SqlConnection conn;
private SqlDataAdapter programmersadapter;
private SqlDataAdapter softwaresadapter;
protected string connectionString = "Data Source=ICEBOX19-PC\\ICEBOX;Initial Catalog=software;Integrated Security=True";
public Form1()
{
InitializeComponent();
conn = new SqlConnection(connectionString);
SqlCommand programmersselect = new SqlCommand("SELECT ID, Name FROM programmers", conn);
programmersadapter = new SqlDataAdapter(programmersselect);
SqlCommand softwaresselect = new SqlCommand("SELECT name FROM softwares WHERE programmerid = #ID", conn);
softwaresselect.Parameters.Add(new SqlParameter("#ID", SqlDbType.Int));
softwaresadapter = new SqlDataAdapter(softwaresselect);
showme();
}
private void showme()
{
ds = new DataSet();
conn.Open();
programmersadapter.Fill(ds, "programmers");
conn.Close();
listBox1.ValueMember = "id";
listBox1.DisplayMember = "name";
listBox1.DataSource = ds.Tables["programmers"];
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
command.ExecuteNonQuery();
conn.Close();
reload();
}
private void reload()
{
//listBox2.SelectedIndexChanged -= listBox2_SelectedIndexChanged;
softwaresadapter.SelectCommand.Parameters["#id"].Value = listBox1.SelectedValue;
var table = new DataTable();
softwaresadapter.Fill(table);
conn.Close();
listBox2.DisplayMember = "name";
listBox2.ValueMember = "id";
listBox2.DataSource = table;
//listBox2.SelectedIndexChanged += listBox2_SelectedIndexChanged;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
reload();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox2.Text;
textBox1.Text = textBox1.Text.Replace(" ", "");
}
}
I get this exception:
The multi-part identifier "System.Data.DataRowView" could not be bound.
It comes from the command.ExecuteNonQuery() in the button1.Click.
I've tried to change the :
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue, conn);
to
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
But I also get the same thing. Do you guys have some ideas ? I am looking for this since 2 hours now.
PS: I get the same error even if I try to delete
private void delete_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("delete from softwares where id="+listBox2.SelectedItem, conn);
command.ExecuteNonQuery();
conn.Close();
}
private void PopulateListBox(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
ls.Items.Add(row["id"]);
}
}
Then, calls
string value = ls.Items[0].ToString();
Well, I have a simple program that is writing to a Database. I am trying to add validation to the textbox like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length < -1)
{
MessageBox.Show("Don't Leave this field blank!");
}
}
catch
{
//todo
}
}
and My save to database code,
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
But still it is adding blank data to the database and strange thing is in the database I have not allowed null but still data is getting added. Any clues where I am wrong?
I don't see you stopping the database to add empty content. You are validating on the textbox_textchanged event which will only validate the text when someone enters the data. You need to put the validation on button1's click event like this:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("Null String !!!!!!!!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
//log
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
An empty textbox.Text has zero byte length , not -1.
To be sure the textbox is not empty you should apply the Trim() to the current text
Also there is no need to catch an exception on this code.
Moreover, don't use the TextChanged event to validate the text box.
There is the Validating event for this purpose. (Remember to set CauseValidation=True for the control)
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
e.Cancel = true;
}
}
of course you could move all the validation in the code where do you update the database
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
return;
}
using(SqlConnection con = new SqlConnection(
"Server=DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
{
SqlCommand sql1 = new SqlCommand("INSERT into Book " +
"VALUES(#text1, #text2,#dtValue", con);
sql1.Parameters.AddWithValue("#text1", textBox1.Text);
sql1.Parameters.AddWithValue("#text2", textBox2.Text);
sql1.Parameters.AddWithValue("#dtValue", dateTimePicker1.Value.ToShortDateString());
con.Open();
sql1.ExecuteNonQuery();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
}