When I sort the data according to the value named "TC NO" and make the edits, all the data in the table changes. For example; I have a, b, and c values. I'm trying to make the value "a" to "d" but the values a,b, and c each convert to the value "d". I just want the value I selected to change. Where am I doing wrong?
public partial class muster_guncelleme : Form
{
public muster_guncelleme()
{
InitializeComponent();
}
static string conString = "Server=localhost;Database=master; Trusted_Connection=True;";
SqlConnection baglanti = new SqlConnection(conString);
private void btn_arama_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "SELECT * from [user] where tc_no=#tc_no";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#tc_no", txt_tc.Text);
SqlDataAdapter da = new SqlDataAdapter(komut);
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
lbl_tc.Text = dr["tc_no"].ToString();
txt_user.Text = dr["user_name"].ToString();
txt_pass.Text = dr["password"].ToString();
txt_name.Text = dr["full_name"].ToString();
bday_date.Text = dr["birth_date"].ToString();
txt_phone.Text = dr["phone_number"].ToString();
}
else
MessageBox.Show("Müşteri Bulunamadı.");
baglanti.Close();
}
private void muster_guncelleme_Load(object sender, EventArgs e)
{
}
private void btn_kaydet_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "update [user] set user_name=#user_name, password=#password, full_name=#full_name, phone_number=#phone_number";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#user_name", txt_user.Text);
komut.Parameters.AddWithValue("#password", txt_pass.Text);
komut.Parameters.AddWithValue("#full_name", txt_name.Text);
komut.Parameters.AddWithValue("#phone_number", txt_phone.Text);
komut.ExecuteNonQuery();
baglanti.Close();
MessageBox.Show("Kullanıcı Bilgileri Güncellendi.");
}
}
Related
I have a program which user can input some data and the data will be storaged into a database (i use Ms Access). But, the program also can do some search of existing data from database. User can input a keyword from textbox and the program will show the data from database.
Like this:
User will input a keyword or a text to "Kd. Dosen" textbox then it will show the data from database contains that keyword. Here is the database:
Can anybody help me how to do this?
Anyway, here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//stri
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryInsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP)values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryInsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dimasukkan!");
}
catch
{
MessageBox.Show("Gagal memasukkan data");
}
finally
{
vconnect.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "update MstDosen set NaDosen = #namadosen, Alamat = #alamat, NoTelp = #notelp, NoHP = #nohp where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil diubah!");
}
catch
{
MessageBox.Show("Gagal mengubah data");
}
finally
{
vconnect.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "delete from MstDosen where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
//vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
//vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
//vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
//vinsert.Parameters.AddWithValue("#nohp", textBox2.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dihapus!");
}
catch
{
MessageBox.Show("Gagal menghapus data");
}
finally
{
vconnect.Close();
}
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
DataList dat = new DataList();
dat.Show();
}
public void insert()
{
if(textBox1.Text != "" && textBox2.Text != "")
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryinsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP) values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryinsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
}
else
{
MessageBox.Show("Data Belum Dimasukkan");
}
}
}
You have to add textbook_change option to double click textbook which you want to write text and filter.
private void txtCariKodu_TextChanged(object sender, EventArgs e)
{
FilterByName();
}
your method is contains a variable which is your db query like (SELECT * FROM YOUTRABLE WHERE NAME LIKE % ).
and now you can show filtered values on your Datagridview.
public void FilterByName()
{
var result = YOURSQLQUERY.ToList();
dataGridView1.DataSource = result;
}
when I have code in my 'SQL string' with "+sqlwhwew+" variable,
excel cant show any contents,
except this case,others case are fine.
if i remove "+sqlwhere+",it can export to excel.
public partial class ExportEmployeeReport : BPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
TWDKM.Web.Common.ExportToExcel(this, "report");
}
protected void rptPremissionList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
}
private void SplitPage1_GoToPage(object sender, EventArgs e)
{
BindData();
}
protected DataSet CreateDataSource(string SQL)
{
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["DataAccessQuickStart1"].ConnectionString;
try
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(connstr);
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.CommandTimeout = 0;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception ErrorInfo)
{
return null;
}
}
protected void BindData()
{
string DDD = "5010";
string CCC = "9511";
string AAA = "9501";
string BBB = "9531";
string sqlwhere = string.Empty;
sqlwhere += #" (o.DTYCD2 not LIKE ''%" + AAA + #"%''
)";
sqlwhere += #" AND (DTYCD2 not LIKE ''%" + BBB + #"%''
)";
sqlwhere += #" AND (DTYCD2 not LIKE ''%" + CCC + #"%''
)";
sqlwhere += #" AND (DTYCD2 not LIKE ''%" + DDD + #"%''
)";
string SQL = "select o.DEPTNM as DEPTNM,count(distinct p.UserAccount) as number,round(cast(count(p.UserAccount) AS FLOAT)/nullif( count(o.userid),0),2) as number1,count(distinct case when" **+ sqlwhere +** " then p.UserAccount end) as number2 from V_EmployeeKm as o left join T_UserLog as p on p.UserAccount=o.USERID group by o.DEPTNM";
DataSet ds = CreateDataSource(SQL);
//string SQL = "select dbo.F_GetUserNameById(UserID) AS Name,dbo.F_Get_EmpyDeptbyID(UserID) AS Dept,Year,(Select MovieClassName from T_ELearnMovieClass where MovieClassID=MovieClassFK) AS MovieClass,sum(TotalTime) as TotalTime from T_MoviePlayedTime group by MovieClassFK,Year,UserID order by Name , Dept ,Year";
if (ds != null && ds.Tables[0].Rows.Count>0)
{
this.rptPremissionList.DataSource = ds.Tables[0];
this.rptPremissionList.DataBind();
}
}
}
it shows error that excel name no match and no contents in excel.
please help me how to correct it
I am trying to make cascading combo boxes. When I select values in combo boxes for the first time everything is OK, but when I return to first combo box and change to some other value, new items in the other combos are appended to the old items. This is my code bellow:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
private void FillStreet(String IdCity)
{
//cityCombo.Items.Clear()
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}
Try this:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
ds.Tables["Location"].Clear();
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
if(!String.IsNullOrWhiteSpace(IdLocation))
{
ds.Tables["City"].Clear();
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
}
private void FillStreet(String IdCity)
{
if(!String.IsNullOrWhiteSpace(IdCity))
{
s.Tables["Street"].Clear();
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(locationCombo.SelectedValue != null)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(cityCombo.SelectedValue != null)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}
}
Since cityCombo.Items.Clear() is not an option in this case as mentioned in the code comments, you can clear the datatable instead:
ds.Tables["City"].Clear();
And in order to avoid the NullReferenceException in cityCombo_SelectionChanged you can check the cityCombo.SelectedValue for null.
You are reusing the DataSet everywhere. So it will keep appending. As I said in the comments, either clear the DataSet or make a local one to each function.
I have been staring at this UPDATE statement for a long while and are unsure why my table isn't changing. When I press the button no error appears but my table doesn't not get updated either, I have checked that all of my variables have values on debug and they do.
I'd appreciate any help anyone can give me!
This is the code that contains the statement I need help with:
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
This is the whole code for my form if anyone wanted to look at it just in case that is affecting the button even handler:
namespace ComputingA2_Official_Project
{
public partial class CurrentlySetTestForm : Form
{
Timer loopTimer = new Timer();
private int CurrentQuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) AS QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=#Signedinstudent AND [StudentAnswer] IS NULL )", connect);
command18.Parameters.AddWithValue("#Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
CurrentQuestionID = Convert.ToInt32(reader[0]);
SqlCommand command19 = new SqlCommand("SELECT ([Question Space]) FROM Questions WHERE ([QuestionID]=#CurrentQID)", connect);
command19.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
using (SqlDataReader reader2 = command19.ExecuteReader())
{
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2[0]);
label1.Text = QuestionSpace;
}
}
}
connect.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
I believe the issue is that you are executing the command asynchronously (BeginExecuteNonQuery), but never calling EndExecuteNonQuery to commit it. I also suspect you could just call it synchronously like this:
command20.ExecuteNonQuery();
I have three combo-box which filtering value in different tables. For the first two combo-box i have no problem but for the third combo-box, I got error show input strings was not in correct format. I using the same code for the other two and it working correctly. Can someone specify how to troubleshoot this problem?
Here my code:-
This one is for combobox two which worked perfectly:-
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
This is the code which show error
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedValue.ToString() != null)
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
I hope someone can show me how to rectify this problem. Thanks.
***UPDATE****
Here the full code
private void FillPier(int BridgeID)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, PierName, BridgeID FROM tbPier WHERE BridgeID = #BridgeID";
cmd.Parameters.AddWithValue("#BridgeID", BridgeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbPier.DataSource = objDs.Tables[0];
cbPier.DisplayMember = "PierName";
cbPier.ValueMember = "PierID";
}
}
private void FillDataPoint(int PierDP)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, InspectDate FROM tbDatapoint WHERE PierID = #PierID";
cmd.Parameters.AddWithValue("#PierID", PierDP);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbInspect.DataSource = objDs.Tables[0];
cbInspect.DisplayMember = "InspectDate";
cbInspect.ValueMember = "PierID";
}
}
private void ViewBridge_Load(object sender, EventArgs e)
{
FillBridge();
}
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedIndex != 1)
{
int PierDP = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierDP);
}
}
Check if this can be converted to int first like this:
int x = 0
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (Int32.TryParse(cbPier.SelectedValue.ToString(), out x))
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
Or using the SelectedIndex property:
if(cbPier.SelectedIndex != -1)
{
.....
}
What are the cbPier.DisplayMember and cbPier.ValueMember ? Is the diplay member the string and value member the int? Double check if that's the case first ...