Asp.net code :
Select Employee : </b>
<asp:DropDownList ID="DropDownListSelectEmployee" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownListSelectEmployee_SelectedIndexChanged"
OnTextChanged="DropDownListSelectEmployee_TextChanged" >
</asp:DropDownList>
Code behind :
public void DropDownListSelectEmployee_Fill()
{
DropDownListSelectEmployee.Items.Clear();
string q = "select username from nworksuser where _type='Employee' or _type='Admin_Employee';";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
string user = "";
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
conn.Close();
}
protected void DropDownListSelectEmployee_TextChanged(object sender, EventArgs e)
{
string q = "select uid,fname,mname,lname,date_format(hire_date,'%Y-%m-%d'),desg,date_format(dob,'%Y-%m-%d'),AddressLine1,AddressLine2,state,city,pincode,country,MobileNo,UserActive,username,date_format(annivarsary,'%Y-%m-%d'),email from nWorksUser where Username='" + DropDownListSelectEmployee.Text + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(q, conn);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
txtFirstName.Text = dr[1].ToString();
txtMiddleName.Text = dr[2].ToString();
txtLastName.Text = dr[3].ToString();
txtMobile.Text = dr[13].ToString();
txtUsername.Text = dr[15].ToString();
txtState.Text = dr[9].ToString();
txtPincode.Text = dr[11].ToString();
txtEmail.Text = dr[17].ToString();
txtDob.Text = dr[6].ToString();
txtDesignation.Text = dr[5].ToString();
txtDateofHire.Text = dr[4].ToString();
txtDateofAnnivarsary.Text = dr[16].ToString();
txtCountry.Text = dr[12].ToString();
txtCity.Text = dr[10].ToString();
txtAddressLine2.Text = dr[7].ToString();
txtAddressLine1.Text = dr[8].ToString();
if (dr[14].ToString().Length == 4)
{
RdoGender.SelectedIndex = 1;
}
else
{
RdoGender.SelectedIndex = 2;
}
conn.Close();
}
}
protected void DropDownListSelectEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
}
Drop down list contains users name from database. Now I want that, as you select any user from drop down list it should show his details in form and its working. But problem is that after choosing any one user, that name appears in drop down for moment and reset it to the first name of drop down list any showing details of its related instead of selected. Its not accepting any other name except first name drop down list. I am not getting where is the problem. Please help me.
You need to wrap the code in DropDownListSelectEmployee_Fill with if (!Page.IsPostBack). On a post back the drop down contents will be repopulating, causing its state to reset, which is why you're seeing the "unexpected behaviour".
Checking for post backs, you can make certain the drop down isn't affected on a selection change:
public void DropDownListSelectEmployee_Fill()
{
if (!Page.IsPostBack)
{
DropDownListSelectEmployee.Items.Clear();
string q = "select username from nworksuser where _type='Employee' or _type='Admin_Employee';";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
string user = "";
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
conn.Close();
}
}
Related
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
In page load I'm loading a drop down list with names from a postgreSQL database, using SQL.
Later in the code I want to save the selected value in the drop down list into a string variable.
That won't happen. What happens is the first value in the list (index 0) always saves, no matter of which I have selected.
Heres is page load (works fine):
protected void Page_Load(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
Here is Button1_Click. I want to save the selected value into string variable syv.
protected void Button1_Click(object sender, EventArgs e)
{
string syv = ddPersons.SelectedItem.Text;
string name = txtName.Text;
int studentid = 0;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sSYS;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT id FROM tbl_student WHERE name = '" + name + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
studentid = (int)dr["id"];
}
}
I have tried
string syv = ddPersons.SelectedItem.Text;
string syv = ddPersons.SelectedItem.Value;
string syv = ddPersons.Text;
string syv = ddPersons.SelectedValue;
It might be that ViewState is saving the state of your page. Why don't you include the following line in your Page_Load method:
if ( !IsPostBack)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
It will prevent the Page_Load to populate duplicate items every time someone clicks on the button and prevents the ViewState to interfere with the state of your controls.
I am trying to get next rows from the table of access database but I am getting last row all time.
Please guide me how to loop through all rows?
Here is the code:
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; DataSource=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
=It`s must outside a button click:
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
con1.Close();
Its must inside button click. You must make i property of form
if(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
But i think it`s may rewrite to more beauty solve.
Sounds like you are after something like
private int _currentRecordId = -1;
...
string cmdStr = String.Format("SELECT * FROM Table WHERE id > {0} ORDER BY id LIMIT 1", _currentRecordId);
using (var con = new OleDbConnection(constr))
using (var com = new OleDbCommand(cmdStr, con))
{
con.Open();
using(var reader = com.ExecuteReader())
{
while (reader.Read())
{
_currentRecordId = reader.GetInt32(0); // whatever field the id column is
// populate fields
}
}
}
On first call this will retrieve the first record with an ID > -1. It then records whatever the ID is for this record so then on the next call it will take the first record greater than that e.g. if the first record is id 0 then the next record it will find is 1 and so on...
This only really works if you have sequential IDs of course.
Assuming that your table is not big (meaning it contains a manegeable number of records) you could try to load everything at the opening of your form and store that data in a datatable.
At this point the logic in your button should simply advance the pointer to the record to be displayed.
private DataTable data = null;
private int currentRecord = 0;
protected void form_load(object sender, EventArgs e)
{
using(OleDbConnection con1 = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("select * from table", con1))
{
con1.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
data = new DataTable();
da.Fill(data);
}
DisplayCurrentRecord();
}
}
private void DisplayCurrentRecord()
{
label1.Text = String.Format("{0}", data.Rows[currentRecord][1]);
RadioButton1.Text = String.Format("{0}", data.Rows[currentRecord][2]);
RadioButton2.Text = String.Format("{0}", data.Rows[currentRecord][3]);
RadioButton3.Text = String.Format("{0}", data.Rows[currentRecord][4]);
RadioButton4.Text = String.Format("{0}", data.Rows[currentRecord][5]);
}
protected void btn_clk(object sender, EventArgs e)
{
if(currentRecord >= data.Rows.Count - 1)
currentRecord = 0;
else
currentRecord++;
DisplayCurrentRecord();
}
Keep in mind that this is just an example. Robust checking should be applied to the rows (if they contains null values) and if there are rows at all in the returned table. Also, this is a poor man approach to the problem of DataBindings in WinForm, so perhaps you should look at some tutorials on this subject
Hope your table is not really named Table, that word is a reserved keyword for Access
simply remove the for loop to fetch record one by one
int lastFetchedRecordIndex=2;
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
string cmdstr = "select * from table where id = " + lastFetchedRecordIndex;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
lastFetchedRecordIndex++;
con1.Close();
}
I have a datagridview, and some data in the table.
The datagridview allows users to enter new rows of data
Question here:
I would like to know how can I get the new inserted rows of data(no matter how many rows have been added) into database without adding the existing data which will then be duplicated.
Anyone?
EDIT: im using sql database, and this is my datagridview.
the data shown is already inside database, now, what if users insert NEW MULTIPLE rows of data into the datagridview? what is the code should I put?
My code as below :
private void button1_Click(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i<dataGridView1.Rows.Count; i++ )
{
String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (#SupplierName, #CostPrice, #PartsID)" ;
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("#SupplierName", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#CostPrice", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#PartsID", textBox1.Text);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
Heres my Insert,cancel and delete statement:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();
if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (ID,TRANS_CD) VALUES(CIS.S_CIS_TRANS.nextval,'')", "ProjectCISConnectionString");
gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;
}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");
gv.DataBind();
}
}
do you have a sqlcommandbuilder, dataAdapter, and dataTable declared?
for example:
SQLConnection con = (your connection);
SQLDataAdapter = sda;
SQLCommandBuilder = scb;
DataTable = dt;
private void btnEnter_Click(object sender, EventArgs e)
da = new SqlDataAdapter("SELECT * FROM [table] WHERE [columnA]='" + txtData.Text + "' OR [columnB]='" + txtData.Text + "' OR [ColumnC]='" + txtData.Text + "' OR [ColumnD]='" + txtData.Text + "'", con);
ds = new DataSet();
dt = new DataTable();
ds.Clear();
da.Fill(dt);
dg.DataSource = dt;
con.Open();
con.Close();
private void btnUpdate_Click(object sender, EventArgs e)
{
//when button is clicked, the SQL Database gets updated with the data that is plugged into the datagridview.
scb = new SqlCommandBuilder(da);
da.Update(dt);
}
what kind of database you have? Here is my source code for oracle database. If its a SQL database replace the : with #.
Source code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectCISConnectionString %>" ProviderName="<%$ConnectionStrings:ProjectCISConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM CIS.CIS_TRANS ORDER BY ID ASC"
DeleteCommand="DELETE FROM CIS.CIS_TRANS WHERE ID = :ID"
InsertCommand="INSERT INTO CIS.CIS_TRANS (TRANS_CD,FUND_CD,BSA_CD,DP_TYPE,TRANS_CD_DESC) VALUES (:TRANS_CD,:FUND_CD,:BSA_CD,:DP_TYPE,:TRANS_CD_DESC)"
UpdateCommand="UPDATE CIS.CIS_TRANS SET TRANS_CD = :TRANS_CD, FUND_CD = :FUND_CD, BSA_CD = :BSA_CD, DP_TYPE = :DP_TYPE, TRANS_CD_DESC =:TRANS_CD_DESC WHERE ID = :ID">
</asp:SqlDataSource>
Your also going to need a query page and some other stuff, please let me know more information.
I do something like this. Quick easy and seems to work fine :
cmd1.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
foreach (GridViewRow row in your_grid.Rows)
{
Label id = (Label)row.FindControl("your_control"); //what ever control you are using
SqlCommand cmd1 = new SqlCommand();
cmd1.CommandText = "insert into your_table values (#p,#p1,#p2)";
cmd1.Parameters.Add("#p", SqlDbType.VarChar).Value = your_control.Text;
cmd1.Parameters.Add("#p1", SqlDbType.VarChar).Value = your_control.Text;
cmd1.Parameters.Add("#p2", SqlDbType.VarChar).Value = your_control.Text;
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
}
this.sqlConnection1.Close();