Access 2003 db
Field Name Data Type
CriminalOffence Text
VS 2010 C#
Using a groupbox, I can store data from radiobutton into my db. I have databinded both groupbox and radiobuttons to my db. When I use my nativgation buttons I see the data that has been stored where the groupbox text is. So the problem is I don't know how to properly retrieve data for the radiobutton. Retrieving data from textbox and combox is showing as it should be. Also when I want to insert new data the radiobutton does not get cleared. So...
I have two radiobuttons named, 1) rBYes 2) rBNo
I have the following method for inserting record...
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#txtID, #AcBAG, #cBGender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cBAG.Text);
cmd.Parameters.AddWithValue("#Gender", cBGender.Text);
string str = "";
if (rBYes.Checked)
{
str = "Yes";
}
if (rBNo.Checked)
{
str = "No";
}
cmd.Parameters.AddWithValue("#CriminalOffence", SqlDbType.NVarChar).Value =
str;
}
And a method for creating a new record
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
cBAG.Text = "";
cBGender.Text = "";
rBYes.Text = "";
rBNo.Text = "";
}
An example of navigation button..
private void btnNextRec_Click(object sender, EventArgs e)
{
this.table1BindingSource.MoveNext();
}
ConnectionString...
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\..
\Database1.mdb");
Please can someone help me here, thanks in advance
Parameter names must match the parameters in the SQL insert statement.
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#ID, #AgeGroup, #Gender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cbAG.Text);
cmd.Parameters.AddWithValue("#Gender", cbGender.Text);
cmd.Parameters.AddWithValue("#CriminalOffence", ((rBYes.Checked)? "Yes":"No"));
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
Related
Why does my grid view not refresh with data in it? It adds to the database but then clears my grid view and has nothing in it. It loads the form and I can enter information into it hit the add button and it adds to database but grid view refresh puts no data into it.
private void addButton_Click(object sender, EventArgs e)
{
string title = titleTextBox.Text;
string starring = starringTextBox.Text;
string year = yearTextBox.Text;
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=<PATH TO FILE>);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dbo.Movie (Title, Starring, Year) VALUES (#title, #starring, #year)";
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#Starring", starring);
cmd.Parameters.AddWithValue("#Year", year);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
SqlDataAdapter MyDataAdapter = new SqlDataAdapter(cmd.CommandText, conn);
titleTextBox.Text = "";
starringTextBox.Text = "";
yearTextBox.Text = "";
titleTextBox.Focus();
movieTableAdapter.Fill(moviesDataSet.Movie);
movieBindingSource.DataSource = movieTableAdapter;
myDataGridView.DataSource = movieBindingSource;
myDataGridView.Refresh();
myDataGridView.Update();
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'moviesDataSet.Movie' table. You can move, or remove it, as needed.
this.movieTableAdapter.Fill(this.moviesDataSet.Movie);
}
SqlDataAdapter MyDataAdapter = new SqlDataAdapter("select query here", conn);
Pass select query to adapter. You are passing an insert query.
I am trying get value from GridView and decrement it that works. However, inserting to the database does not work. What's wrong?
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
m = GridView1.SelectedRow.Cells[5].Text;
int nm = Convert.ToInt32(m);
if (GridView1.SelectedRow.Cells[5].Text != "")
{
cn.Open();
nm--;
cmd.CommandText = ("INSERT INTO rezerwacje [miejsca] VALUES(#nm)");
//cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
}
}
Seems you are not adding the parameter value
cmd.CommandText = ("INSERT INTO rezerwacje [miejsca] VALUES(#nm)");
cmd.Parameters.Add(new SqlParameter("nm", nm));
I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.
rIdThere are two text boxes in page. One is for UserId and the other one is for email. Both are retrieved data from table aspnet_membership and are set 'read-only'.
For email text box, it will change read-only = false. Then user get to enter a new email then hit button save. It should update the email in table with the new email but unfortunately no changes made. Can some one tell me what should I remove/add to make it works. Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
protected void Button4_Click(object sender, EventArgs e)
{
TextBox2.ReadOnly = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
}
I have refatored your code, now it should work
protected void Button3_Click(object sender, EventArgs e){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
try {
conn.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
throw ex;
}
finally{
conn.Close();
}
}
Look like you forgot to open connection
con.Open();
run command
cmd.ExecuteNonQuery();
and then close connection
con.Close();
You code is showing no signs of committing any data back to its Data Source.
You need a Data Adapter, and you need to set its Insert Command to the command above.
SQLDataAdapter adapt = new SQLataAdapter();
you then need to open a connection :-
conn.open();
adapt.UpdateCommand = cmd;
adapt.UpdateCommand.ExecuteNonQuery()
conn.close();
Hope This Helps.
You can try directly updating the user via Membership class in your button click event:
protected void Button3_Click(object sender, EventArgs e)
{
var memUser = Membership.GetUser(TextBox3.Text) //Fetch the user by user Id
memUser.Email = TextBox2.Text // Assign the new email address
Membership.UpdateUser(memUser) // update the user record.
}
Is there any way to do autocomplete for domain users in .net?
Meaning, I want a textbox that when I will start and type Admin, it will complete it to \Administrator
Thanks.
Sure, you can hold a list of all valid domain account names and use an autocomplete (winforms example) with that data source.
Of course, this means you are exposing some sensitive information.
you can try like this for displaying domain user names ......
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection = ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" + " order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show(" this is autocomplete text box example");
}
}
}