I am working on a visual web part that does simple CRUD operations and I have this strange behavior in Page_load().
I grab first record from query and assign some text fields when page is loaded. When I clear the form and update the form with new different inputs, those text fields remember the first values and ignores newly entered data.
Am I missing anything in Page_load() when I display data when the page is loaded?
public partial class VisualWebPart1UserControl : UserControl
{
string connstr = AdminDashBoard.Utility.GetConnectionString();
private DataSet sqlDst = new DataSet();
private static int RowNo = 0;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
string strQuery = "xxxxxxxxxxxxxxxxxxxxxx";
try
{
conn.Open();
SqlCommand sqlCmd = new SqlCommand(strQuery, conn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd);
sqlAdap.Fill(sqlDst);
//these fields remember first assigned data!!!
this.TextBox1.Text = sqlDst.Tables[0].Rows[RowNo][0].ToString();
this.TextBox2.Text = sqlDst.Tables[0].Rows[RowNo][1].ToString();
this.TextBox3.Text = sqlDst.Tables[0].Rows[RowNo][2].ToString();
this.DateTimeControl1.SelectedDate = Convert.ToDateTime(sqlDst.Tables[0].Rows[RowNo][3].ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
conn.Dispose();
}
}
thanks in advance
Related
I'm fairly new to C# and coding in general. I've looked through similar questions and didn't have much luck fixing this.
I am making an app that stores Student details for attendance in tables, in a database. Currently when I run it, the details are added to the tables from textboxes. A button opens a separate form with a datagridview, but the details are not updated in this. If I rerun the application and open the second form, the datagridview has been updated. How do I get the datagridview to update based on information added to the table while the application is running?
This is the code that adds the details to the table
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\corry\Desktop\StudentAttendanceBurton\Attendance.mdf;Integrated Security=True";
sc.Open();
using (SqlCommand com = sc.CreateCommand())
{
com.CommandText =
"insert into BUS102(\n" +
" Name,\n" +
" [Student ID],\n" +
" Date)\n" +
"values(\n" +
" #prm_Name,\n" +
" #prm_Student_ID,\n" +
" #prm_Date)";
com.Parameters.Add("#prm_Name", SqlDbType.NVarChar, 50).Value = student.Name;
com.Parameters.Add("#prm_Student_ID", SqlDbType.Int).Value = student.StudentID;
com.Parameters.Add("#prm_Date", SqlDbType.SmallDateTime).Value = student.Date;
com.ExecuteNonQuery();
}
}
This is the code for the form that has the datagridview
public partial class AttendanceForm : Form
{
public AttendanceForm()
{
InitializeComponent();
}
private void bUS102BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bUS102BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.attendanceDataSet);
}
private void AttendanceForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'attendanceDataSet.BUS102' table. You can move, or remove it, as needed.
this.bUS102TableAdapter.Fill(this.attendanceDataSet.BUS102);
}
}
public partial class Form1 : Form {
private DataSet m_ds = new DataSet();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using (SqlConnection conn = new SqlConnection(#"Data Source=YOURSql;Initial Catalog=YOURDB;Integrated Security=True")) {
// set command
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(m_ds);
// bind data to dataGrid
dataGridView1.DataSource = m_ds.Tables[0];
// refresh Data
dataGridView1.Refresh();
conn.Close();
}
}
private void cmdChangeData_Click(object sender, EventArgs e) {
// add new row explicit
DataRow nr = m_ds.Tables[0].NewRow();
nr[0] = "0000";
nr[1] = "xxxx";
// add new row to DataSet (just in memory, NOT TO DB)
m_ds.Tables[0].Rows.Add(nr);
// Refresh Data
dataGridView1.Refresh();
}
}
You have to refresh datagridview
this.dataGridView1.Refresh();
So I'm trying to create sort of an overview utility of sites, with different infos on each site.
I'd like to have a dropdown list / combobox, reading a sqldb and create items according to the db. Then I would like different textboxes to get populated with a value from a column.
Say my db table is called "AvSites" so far (just for the sake of it) i have "projectNr", "siteName", "siteClients" and "siteLicenses" columns I'd like each of these to populate some textbox / label somewhere.
I've tried the following, which kinda works, Ive had the code working most of the time, but the thing that defeats me is having the data change with the combobox item selected.
I hope you can help, and so here is my code so far (I have a login window, before this "main" program starts, just so you're not wondering)
And I'm quite new to C# so if there's something thats done inefficient thats the reason :) Im still learning.
namespace AvOverview{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
//btn_LogOut Click Event
this.Hide();
Form1 fl = new Form1();
fl.Show();
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void FrmMain_Load(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
cmd.ExecuteNonQuery();
con.Close();
}
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
string strCmd = "select id from AvSites";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(strCmd, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{//this last part is solely for testing if the text changed the way I wanted.
label1.Text = dr.GetValue(1).ToString();
label2.Text = dr.GetValue(2).ToString();
label3.Text = dr.GetValue(0).ToString();
label4.Text = dr.GetValue(3).ToString();
You don't need to call the database again. All the info are in the current selected item.
When you set the DataSource of your combo to a datatable like you do in the click event each element of the combo is a DataRowView and from this element you can get all the info extracted from the database from your initial query
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = Combo1.SelectedItem as DataRowView;
if(rv != null)
{
label1.Text = rv[1].ToString();
label2.Text = rv[2].ToString();
label3.Text = rv[0].ToString();
label4.Text = rv[3].ToString();
}
}
Side note: There are some improvements needed in your code.
First you should store the connection string in the config file and read it back with the ConfigurationManager class. Read about Configuration in NET
Second you shouldn't work with disposable objects like you do now. A disposable object should be disposed as soon as you have finished to use it. In particular the SqlConnection keeps valuable system resources both on your machine and on the server. You should start to use the using statement
string strCmd = "select * from AvSites";
using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(strCmd, con)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
// ??? not needed ==> cmd.ExecuteNonQuery();
// not needed with using ==> con.Close();
}
// Here the connection is closed and disposed and resources are released
I'm making a gallery site. And it plots the available photography sessions that are on the database.
But when the user first opens the page, no photography sessions are selected. So the page would be empty. I want to automatically select the first session for the user. I did it by selecting the first record in the database. But i really wish if i could just write a code inside the Page_load that auto clicks on the first item inside the repeater.
The repeater items are dynamically generated of course. So i don't know if i could achieve this using JavaScript or not.
Here's my code :
protected void Page_Load(object sender, EventArgs e)
{
DataSet dst = new DataSet();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlDataAdapter adbtr = new SqlDataAdapter();
adbtr.SelectCommand = new SqlCommand("SELECT * FROM dbo.Select_gallery_names_FN()", con);
try
{
int result = adbtr.Fill(dst);
if (result == 0)
{
return;
}
cat_repeater.DataSource = dst;
cat_repeater.DataBind();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
using (SqlConnection img_con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlDataAdapter img_adbtr = new SqlDataAdapter();
img_adbtr.SelectCommand = new SqlCommand("select * from dbo.Select_gallery_cat_FN(#img_cat)", img_con);
img_adbtr.SelectCommand.Parameters.Add("#img_cat",SqlDbType.NVarChar,8000).Value = dst.Tables[0].Rows[0][0].ToString();
DataSet img_dst = new DataSet();
try
{
img_adbtr.Fill(img_dst);
slider_repeater.DataSource = img_dst;
slider_repeater.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected void cat_repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from dbo.Select_gallery_cat_FN(#img_cat)";
cmd.Parameters.Add("#img_cat", SqlDbType.NVarChar,8000).Value = ((LinkButton)e.CommandSource).Text;
con.Open();
slider_repeater.DataSource = cmd.ExecuteReader();
slider_repeater.DataBind();
}
}
You could do something like this.
<script>
$(document).ready(function() {
$('#cat_repeaterId').find('tr:first').click();
});
</script>
Might have to mess around with the javascript depending on if you want to click a button inside the first row.
I have two combobox in my form, using a mysql connection to a remote server. The first combobox populated nicely. However, I need the indexid since that is a foreign key to populate a second combobox. Based on the selection, it will change the data in the second combo (for the xample, i the first combo is for car makes, then the models of each make gets filled, so if I choose Nissan, the models will then have Altima, Maxima, Sentra, ... but if I chose Toyota, the combo will then show Corolla, Camry, Prius, ...)
My foreign key is always -1 for some reason. I am using the selectindex change method, but it keeps crashing/ bc the value is always -1.
I am very new to MySQL in C# and eager to learn. Any help is appreciated. The code is below.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMake.SelectedIndex >= 0)
cboModel.Enabled = true;
else
cboModel.Enabled = false;
// get the foreign key value of the model id to get the make for each brand to populate here
// MessageBox.Show(cboModel.ValueMember);
// right now selectindex always shows -1. why?
// if it changes, you need to then enable the right cbo, else, disable.
// but also, you need the mid, fk, so you can then do a new sql statement with the where clause to populate it.
int fk = cboModel.SelectedIndex;
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid='fk'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "model";
cboMake.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
private void frmMain_Load(object sender, EventArgs e)
{
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_make";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "make";
cboMake.ValueMember = "mid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
Correct me if I'm wrong, but considering code provided, just a guess :
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int fk = cboModel.SelectedIndex; // ?????
.....
}
You access here cboModel, which is not that one whom item was actually selected. At least lookin on event name cboMake_SelectedIndexChanged, seems to me that you should look on cboMake selected index.
Hope this helps.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int foreignKey = (int)cboMake.SelectedIndex +1; // i forgot to cast the int from string since the database was tinyint, it still returns string in c#
string fk = foreignKey.ToString(); // since i need the string for the query, back it goes, but i needed to do arithmetic
string connStr = "server=10.18.30.1;user=notroot;database=car;port=3306;password=password";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid=" + fk; // forgot to escape out of the string (used to php $var style within double quotes)
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboModel.DataSource = dt; // i had cboModel by a silly mistake
cboModel.DisplayMember = "model";
cboModel.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
i have two drop down list in web form..for both of them i've used following code to bind with sql..but whenever i'm trying to bind second drop down list with same method..it's giving error..
the code i've used:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlPropertyType.AppendDataBoundItems = true;
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select ID, PropertyName from PropertyType";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlPropertyType.DataSource = cmd.ExecuteReader();
ddlPropertyType.DataTextField = "PropertyName";
ddlPropertyType.DataValueField = "ID";
ddlPropertyType.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}
You want to create two dropdownlists with a dependency between them.
You need to enable AutoPostBack in the "parent" dropdownlist, add the changed event to it, and in the event load your "child" dropdownlist.
You have a good example here: http://www.aspsnippets.com/Articles/Creating-Cascading-DropDownLists-in-ASP.Net.aspx
u can directly bind dropdown using sql data base.......no need to do cding