asp.net c# dropdown list findbytext keeps adding item? - c#

May be a noob question. But I am scratching my head what I am doing wrong here.
protected void ddlClientNum_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Bussiness.GetConnectionString("Default")))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select distinct client_name from [dbo].[customer_master] where client_number=" + ddlClientNum.SelectedItem.Text + " order by client_name", con);
adapter.Fill(dt);
ddlClientName.DataSource = dt;
ddlClientName.DataTextField = "client_name";
ddlClientName.DataValueField = "client_name";
ddlClientName.DataBind();
ddlClientName.ClearSelection();
//ddlClientName.SelectedValue = ddlClientName.Items.FindByText((ddlClientNum.SelectedItem.Text).ToString()).Value;
//ddlClientName.SelectedValue = ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()).Value;
//ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()).Selected = true;
ddlClientName.SelectedIndex = ddlClientName.Items.IndexOf(ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()));
}
}
}
I am populating client number and client name dropdownlist on page load. On selection of client number I need to select the respective client name but I don't want to Clear the Items. I need users to be able to see the other client names but need to Select the Client name for selected client Number. I Have tried the 3 things but it keeps adding the selected client name.
So, selected client name is occurring as many times I select the respective Client Number and stays there even if I select another client Number.
e.g. I select Client Number :176 | Client Name shows "XYZ Client" selected but occurs twice in the list. If I select any other client number and then again select 176 I can see "XYZ Client" occuring in the list thrice.
Blues and yellows are the repeating ones.

Then you don't need to bind again here. just set the selected index.
Also, I suggest you to use Parameterized queries. Otherwise, It will be vulnerable to SQL injection.
For more info : https://www.mssqltips.com/sqlservertip/2981/using-parameters-for-sql-server-queries-and-stored-procedures/
protected void ddlClientNum_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Bussiness.GetConnectionString("Default")))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select distinct client_name from [dbo].[customer_master] where client_number=" + ddlClientNum.SelectedItem.Text + " order by client_name", con);
adapter.Fill(dt);
ddlClientName.ClearSelection();
ddlClientName.SelectedIndex = ddlClientName.Items.IndexOf(ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()));
}
}
}

Related

How can I retrieve data from my PostgreSQL database? WPF/C#

For reference, I am new to C#/WPF/PostgreSQL and I am trying to create a project for practice, however I've hit a bit of a roadblock. I found this earlier and tried following along with the answers (I understand it isn't 1 to 1) with my own code: Retrieving data from database in WPF Desktop application but it didn't work in my case.
I am creating a simple recipe app where a user can create a recipe (e.g., put in the title, steps, things they need, etc.) and on the home screen, they can see a link to the recipe that was saved, which would take them to the Recipe Screen to be displayed if clicked. I am using PostgreSQL for my database and I do see the correct information on there after the user would submit all of the necessary info, I just need to retrieve it and put it in a data grid possibly? Unless there is a better way other than a data grid.
Regardless, I plan to have it shown as a list of just the title of the recipe, where a user can click on it and it would load up the page, but that's something I can tackle another time if that is outside of the scope in regards to my question.
Here is a visual idea of what I'm trying to accomplish:
Here is my code for the submit button found in the Create Screen if it helps, however I have no idea what to do in terms of actually retrieving that data and then displaying it on my Home Screen.
private static NpgsqlConnection GetConnection()
{
return new NpgsqlConnection(#"Server=localhost;Port=5432;User Id=postgres;Password=123;Database=RecipeProj;");
}
private void SubmitButton_Click(object sender, RoutedEventArgs e)
{
Recipe recipe = new Recipe();
recipe.Title = TitleBox.Text;
recipe.Step1 = StepBox1.Text;
recipe.Step2 = StepBox2.Text;
recipe.Step3 = StepBox3.Text;
recipe.Step4 = StepBox4.Text;
recipe.Step5 = StepBox5.Text;
recipe.Step6 = StepBox6.Text;
recipe.Ingredients = IngredientBox.Text;
recipe.Tools = ToolBox.Text;
recipe.Notes = NoteBox.Text;
void InsertRecord()
{
using (NpgsqlConnection con = GetConnection())
{
string query = #"insert into public.Recipes(Title, Ingredients, Tools, Notes, StepOne, StepTwo, StepThree, StepFour, StepFive, StepSix)
values(#Title, #Ingredients, #Tools, #Notes, #StepOne, #StepTwo, #StepThree, #StepFour, #StepFive, #StepSix)";
NpgsqlCommand cmd = new NpgsqlCommand(query, con);
cmd.Parameters.AddWithValue("#Title", recipe.Title);
cmd.Parameters.AddWithValue("#Ingredients", recipe.Ingredients);
cmd.Parameters.AddWithValue("#Tools", recipe.Tools);
cmd.Parameters.AddWithValue("#Notes", recipe.Notes);
cmd.Parameters.AddWithValue("#StepOne", recipe.Step1);
cmd.Parameters.AddWithValue("#StepTwo", recipe.Step2);
cmd.Parameters.AddWithValue("#StepThree", recipe.Step3);
cmd.Parameters.AddWithValue("#StepFour", recipe.Step4);
cmd.Parameters.AddWithValue("#StepFive", recipe.Step5);
cmd.Parameters.AddWithValue("#StepSix", recipe.Step6);
con.Open();
int n = cmd.ExecuteNonQuery();
if (n == 1)
{
MessageBox.Show("Record Inserted");
TitleBox.Text = IngredientBox.Text = ToolBox.Text = NoteBox.Text = StepBox1.Text = StepBox2.Text = StepBox3.Text = StepBox4.Text = StepBox5.Text = StepBox6.Text = null;
}
con.Close();
}
}
InsertRecord();
}
string query = #"select * from Recipes";
NpgsqlCommand cmd = new NpgsqlCommand(query, con);
con.Open();
var reader = cmd.ExecuteReader();
var recipes = new List<Recipe>();
while(reader.Read()){
//Recipe is just a POCO that represents an entire
//row inside your Recipes table.
var recipe = new Recipe(){
Title = reader.GetString(reader.GetOrdinal("Title")),
//So on and so forth.
//...
};
recipes.Add(recipe);
}
con.Close();
You can use this same exact query to fill in a List of titles and a DataGrid that shows all the contents of a recipe.

How can I remove duplicate data from GridView?

I have a GridView which displays data from MySQL database
When I enter the code to display this information, everything works fine. However, after displaying the information, it continues to form duplicates of the same data.
Ex. The gridview would show the table
Customer ID Username Password
1 root root
2 pie root
3 apple root
1 root root
2 pie root
3 apple root
and ongoing..
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string strConn = "server=localhost;user id=root;password=root;database=database";
string sql = "SELECT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";
MySqlConnection conn = new MySqlConnection(strConn);
MySqlDataAdapter dA = new MySqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
conn.Open();
dA.Fill(ds, "entryform,entryform2");
dataGridView.DataSource = ds;
dataGridView.DataBind();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm still fairly new so I am not sure what I did wrong or what else I need to add to fix this error. If anyone can provide any tips, that would be great!
Thanks in advance!
Try this:
dataGridView.Clear();
because maybe you are filling the dataGridView more than once! ;)
If is that you are getting duplicate values from the database, try this:
string sql = "SELECT DISTINCT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";
I hope this helps

JOIN Query working in sql server 2008, unable to load data in datagridview only shows heading

I am trying to load data from different tables created in sql server 2008 based on the values selected from the combo boxes. I had written the query for the same which works perfectly in SQL Server 2008 but doesn't load any data in datagridview but shows the heading of the required data fields from database.
I am completely struck ed. There are no errors. Application works completely fine. Even the query itself is able to execute in query builder.
So I request you all to get me out of this problem. Thanks in advance for any help.
Here is the code:
public partial class ViewTimeTable : Form
{
SqlCommand cm = new SqlCommand();
DataAccess da = new DataAccess();
int d_id, y_id;
public ViewTimeTable()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
d_id = Convert.ToInt32(cmbDepartment.SelectedValue);
y_id = Convert.ToInt32(cmbDepartment.SelectedValue);
SqlDataAdapter dap=null;
string query = "SELECT TimeTable.Day,TimeTable.FromTime,TimeTable.ToTime,
Teachers.TName,Subject.SubName FROM (TimeTable INNER JOIN Teachers ON
TimeTable.T_id = Teachers.T_id INNER JOIN Subject ON TimeTable.Sub_id =
Subject.Sub_id) Where TimeTable.D_id=" + d_id + " AND TimeTable.Y_id=" +
y_id + "";
cm.CommandText = query;
da.Action(cm);
dap=da.GetDataAdapter(cm);
DataTable table = new DataTable();
dap.Fill(table);
dataGridView1.DataSource = table;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
As I read the code, I see:
d_id = Convert.ToInt32(cmbDepartment.SelectedValue);
y_id = Convert.ToInt32(cmbDepartment.SelectedValue);
To my eyes, these are setting d_id and y_id to the same value. I suspect that you want them set to different values.
The reason your query is not working is because no rows meet the condition. If you print out the query after variable substitution, the problem would be obvious.

Retrieve/insert data using SQLiteDataAdapter

I'm currently creating a small application using Windows Forms and SQLite. After reading some tutorials I implemented this method for data retrieval:
public DataTable GetDataTable(ref SQLiteDataAdapter adapter, string sql)
{
DataTable dt = new DataTable();
// Connect to database.
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
// Create database adapter using specified query
using (adapter = new SQLiteDataAdapter(sql, connection))
// Create command builder to generate SQL update, insert and delete commands
using (SQLiteCommandBuilder command = new SQLiteCommandBuilder(adapter))
{
// Populate datatable to return, using the database adapter
adapter.Fill(dt);
}
return dt;
}
(As well as another GetDataTable which doesn't take an SQLiteDataAdapter as parameter)
I have three classes, let's call them UI, Link and Database. The UI does nothing but displaying the data and raising events upon user interaction. The Link creates the Database and a SQLiteDataAdapter, retrieves a data table through the method mentioned above, and binds it to a data grid view on the UI. The user cannot alter the table through the data grid view, but should do so through some text boxes. (does this make binding the table to the dgv obosolete?)
What's the best way to get the user input from the text boxes to the database, using the adapter? Or should I use DataReader and some Insert method instead of an adapter?
As of know, the UI exposes its controls through Get-methods. Is there a better solution?
private void Initialize()
{
// Subscribe to userInterface events
userInterface.DataGridViewSelectionChanged += new EventHandler(userInterface_DataGridViewSelectionChanged);
userInterface.NewClicked += new EventHandler(userInterface_NewClicked);
userInterface.SaveClicked += new EventHandler(userInterface_SaveClicked);
// Get dataGridView from userInterface and bind to database
bindingSource = new BindingSource();
bindingSource.DataSource = database.GetDataTable(ref adapter, "SELECT * FROM SomeTable");
userInterface.GetDataGridView().DataSource = bindingSource;
}
void userInterface_DataGridViewSelectionChanged(object sender, EventArgs e)
{
if (userInterface.GetDataGridView().SelectedRows.Count != 0)
{
DataGridViewRow row = userInterface.GetDataGridView().SelectedRows[0];
userInterface.GetIDTextBox().Text = row.Cells["PrimaryKey].Value.ToString();
userInterface.GetOtherIDTextBox().Text = row.Cells["ForeignKey"].Value.ToString();
DataTable dt = database.GetDataTable("SELECT * from SomeTable WHERE ForeignKey=" + row.Cells["ForeignKey"].Value);
userInterface.GetLastNameTextBox().Text = dt.Rows[0]["LastName"].ToString();
userInterface.GetFirstNameTextBox().Text = dt.Rows[0]["FirstName"].ToString();
userInterface.GetCompanyTextBox().Text = dt.Rows[0]["Company"].ToString();
}
}
void userInterface_NewClicked(object sender, EventArgs e)
{
// Get all text boxes and clear them
// Let the UI take care of this by itself?
}
void userInterface_SaveClicked(object sender, EventArgs e)
{
// Get text/data from all text boxes and insert (or update if editing table) into database
// adapter.Update(...)?
}
Cheers!
INSERT, UPDATE and DELETE operations are the working of a DbCommand. You need a different method that takes the sql string and a collection of SQLiteParameter that you use for the INSERT.
I will try to write some pseudocode for the INSERT operation
public class MyHelperClass
{
public static int InsertCommand(string sql, SQLiteParameter[] parameters)
{
int result = 0;
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
{
cmd.Parameters.AddRange(parameters);
result = cmd.ExecuteNonQuery();
}
return result;
}
}
Now you have to build the parameter array to pass to the help method and this should be done from your UI code
string sqlCommand = "INSERT INTO table1 (FirstName, LastName) VALUES (#fName, #lName)";
SQLiteParameter[] p = new SQLiteParameter[2];
p[0] = new SQLiteParameter("#fName", TextBox1.Text);
p[1] = new SQLiteParameter("#lName", TextBox2.Text);
int rowAdded = MyHelperClass,InsertCommand(sql, p);
The operation for the UPDATE and DELETE command are similar. Also I suggest you to add a version of your GetDataTable that accepts a parameter array instead of building sql commands with string concatenation. As repetead innumerable times here string concatenation leads to errors and, worst of all, to weak code easily exposed to sql injection.

how to Save and Update data from GridView to database in ASP.Net C#?

I developed a web application using ASP.Net C#.
In this application there is a GridView that I fill it with data using ODBCDataAdapter as in the following code:-
protected void Page_Load(object sender, EventArgs e)
{
ConnectionString1 = "DSN=DataSourceName;SRVR=Server;DB=Database;UID=User;PWD=Password;";
OdbcConnection1 = new OdbcConnection(ConnectionString1);
try
{
OdbcConnection1.Open();
CommandText1 = "SELECT * FROM TableName";
DataSet1 = new DataSet();
OdbcDataAdapter1 = new OdbcDataAdapter(CommandText1, OdbcConnection1);
OdbcCommandBuilder1 = new OdbcCommandBuilder(OdbcDataAdapter1);
OdbcDataAdapter1.Fill(DataSet1, "TableName");
DataSet1.AcceptChanges();
myGridView.DataSource = DataSet1;
myGridView.DataMember = "TableName";
myGridView.DataBind();
}
catch (Exception Exception1)
{
Response.Write("<br/>Exception1 Message: " + Exception1.Message);
}
OdbcConnection1.Close();
}
This code works fine and loads the data from dataset to the GridView.
My problem is that I do some changes in that GridView and I would like to save these changes in the real database using the DataSet that should change according to an event of a button click or a specific condition.
I try using the following but it did not work althogh it gives 0 as the result.
OdbcDataAdapter1.UpdateCommand = new OdbcCommand("UPDATE TableName", OdbcConnection1);
OdbcDataAdapter1.Fill(DataSet1,"TableName");
int g = OdbcDataAdapter1.Update(DataSet1,"TableName");
Response.Write("g: " + g);
I tried also the following:-
OdbcCommandBuilder1 = new OdbcCommandBuilder(OdbcDataAdapter1);
try
{
int k = OdbcDataAdapter1.Update(DataSet1, "TableName");
DataSet1.AcceptChanges();
Response.Write("k: " + k);
}
catch (Exception Except)
{
Response.Write("Except: " + Except.Message);
}
as every time I check the database I find no changes although the changes appears in the GridView..
I need to read the Microsoft and MSDN for more examples and code samples about doing the basic database SQL operations (SELECT - INSERT - UPDATE - DELETE) using C#, ASP.NET, and ADO.Net.
The ODBCDataAdapter should be the good way to handle that in case of using Disconnected mode or the ODBCDataReader will be the good way in case of using Online mode.

Categories

Resources