Binding textboxes to database (C# web developer) - c#

I am using Microsoft Visual Web Developer 2010 Express. I have been trying to enter my textbox input into a database table I created. I ran into a problem using the DataBinding property (located under the BindTextBoxes method at the bottom). I searched the internet and found out that the DataBinding property does not exist in Web Developer. Is there an alternate way to transfer the textbox input into a database table?
Here is database part of my code (in C#):
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
//used to link textboxes with database
BindingSource bsUserDetails = new BindingSource();
//info stored in tables
DataSet dsUserDetails = new DataSet();
//manages connection between database and application
SqlDataAdapter daUserDetails = new SqlDataAdapter();
//create new SQL connection
SqlConnection connUserDetails = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Users\synthesis\Documents\Visual Studio 2010\Projects\Practical\Practical\App_Data\UserDetails.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
//link textboxes to relevant fields in the dataset
bsUserDetails.DataSource = dsUserDetails;
bsUserDetails.DataMember = dsUserDetails.Tables[0].ToString();
//call BindTextBoxes Method
BindTextBoxes();
private void BindTextBoxes()
{
txtBoxCell.DataBindings.Add(new Binding("Name entered into txtBox", bsUserDetails,
"Name column in database table", true));
}
}
}

You could always write your own SQL for inserting data from your text boxes. You'll need to setup a SqlConnection and SqlCommand object. Then you'll need to define the SQL on the command and set up the parameters to prevent SQL injection. Something like this:
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO sometable VALUES(#text1,#text2)");
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("text1", text1.Text);
command.Parameters.AddWithValue("text2", text2.Text);
command.ExecuteNonQuery();

Related

How to load the datagridview using OOP C#

I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.

How to Connect DataGridView in C# To an SQL Database?

I'm trying to pass data from DataGridView to a Database SqlClient I opened especially for this. When the program runs, it tells me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I made a form with 2 buttons, one for adding data to the DataGridView (works fine) and another one to pass the data to a database table.
the not working button's code is this:
private void button3_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=.;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "SELECT * FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
con.Open();
dataadapter.Fill(ds, "Authors_table");
con.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
What can I do to fix it?
I tried choosing a data source to the DataGridView but it still didn't work out.
Thanks in advance!

can't find the logical error in c# asp.net below

I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.

Passing a Parameter - ReportViewer local mode

Am tyring to pass a parameter in a local report using a ReportViewer control in VS2010. The user clicks on a merchant, and there is a button press (not shown) which then renders the report.
I've tried using this video : How-to Pass Parameter to Report Viewer - YouTube
Problem: Code doesn't work - near xxxx at the bottom I can't figure out what should be in there
Problem: I would love to get rid of this code and use linqtosql or something simpler.
protected void Page_Load(object sender, EventArgs e)
{
DataSet1TableAdapters.MerchantNamesTableAdapter merchantNamesTableAdapter = new DataSet1TableAdapters.MerchantNamesTableAdapter();
ddlMerchants.DataSource = merchantNamesTableAdapter.GetDataAllMerchants();
ddlMerchants.DataTextField = "Name";
ddlMerchants.DataValueField = "MerchantUID";
ddlMerchants.DataBind();
ReportViewer1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
ReportViewer1.Visible = true;
var newDataSet = new DataSet();
SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=myDataBase;Integrated Security=True");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "select * from merchant where merchantUID = #MerchantUID";
sqlCommand.Parameters.AddWithValue("#MerchantUID", ddlMerchants.SelectedValue);
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(newDataSet);
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();
}
In scenario like this I usually follow this path:
I create a dataset for the report: select the report and the menu command View - Report Data; in the Report Data windows select New ... - Dataset. I enter a name for the dataset (suppose Redemptions) and I select New ... next by DataSource, then I select Object and I navigate to my domain (or dto) class. That done I see the fields of my class and I can use it in the report;
If needed I create parameters in the Report Data Windows (right click on the Parameters Node) and define the name and type of the parameter;
I write this code to pass the data and parameters (if needed) to the report:
viewer.Reset();
ReportDataSource dataSource = new ReportDataSource();
// I use a service/repository; you could also use Linq2Sql or EntityFramework
IList<Redemption> redemptions = _service.GetRedemptions(merchantId);
BindingSource bindingSource = new BindingSource(redemptions, string.Empty);
dataSource.Name = "Redemptions";
dataSource.Value = bindingSource;
viewer.LocalReport.DataSources.Add(getDataSource(sourceInfo));
String reportName = "AD.Conso.MyReport.rdlc";
viewer.LocalReport.ReportEmbeddedResource = reportName;
IList<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("myParameterName", "myParameterValue"));
viewer.LocalReport.SetParameters(parameters);
viewer.RefreshReport();
Note: I took this code from a project where I am using it in a slight different context, so some code could be not necessary in your context.
That xxxx is simply the name of the Datasource that you want to have. it can be anything and is used to by the constructor to Construct a named data source. Its simply an identifier . Like pass "Merchent_Redemptions" or whatever u like.
The datatable is being used as a constructor rather it should be written as an index..
Below is the code present
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
The code should be in this format
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables[0]);
If u have dataAdapator, DataSet then try this on form load:-
this.DataTableAdapter.Fill(this.myDatabase_DataSet.tableName, parameter01, parameter02);
this.reportViewer1.RefreshReport();

Storing the url in SQLSERVER 2005 using C# code(data sets)

I was trying to store the url on button click using the following code.There were no error but the required url is not sroeing in my column field (i used ntext data tpe for this).Please help me if there was some mistake in my code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = new SqlConnection(connection);
//dataset object to store and manipulating data
DataSet myDataSet = new DataSet();
//data adapters to execute SQL
SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM gti_analytics", conn);
myDataAdapter.Fill(myDataSet, "gti_analytics");
myDataAdapter.InsertCommand = new SqlCommand("INSERT INTO gti_analytics [links] VALUES [txt]");
}
protected void Button1_Click(object sender, EventArgs e)
{
String text = "http://google.com";
Storetxt(text);
}
}
The problem is that you're not actually executing the command against the database. You're defining the InsertCommand to use, but it's not being executed.
Based on that code, I don't see that you need to use a DataAdapter/DataSet anyway, just use an SqlCommand to do the insert, which is more lightweight. Something like this:
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(connection);
cmd = new SqlCommand("INSERT INTO gti_analytics (Links) VALUES (#Link)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Link", txt);
conn.Open();
cmd.ExecuteNonQuery();
}
catch{//handle exceptions}
finally
{
if (cmd != null) cmd.Dispose();
if (conn != null)
{
if (conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
}
}
}
I'd also recommend not using ntext for this in your db. If you really need unicode support, use nvarchar which can go up to 4000 chars pre-sql 2005, or nvarchar(max) which can store as much as ntext from SQL 2005 onwards. If you don't need unicode support, use varchar instead (8000 chars pre-sql 2005, VARCHAR(MAX) from SQL 2005 onwards allows same as text)
shouldn't you be calling myDataAdapter.Update() at the end of the Storetxt method?
oh and i think using ntext for this is overkill.
Your txt method argument is not actually used anywhere in your method which is one reason why it's not being stored in the db.
You don't need a SqlDataAdapter or a DataSet for this operation, as AdaTheDev said. Follow the sample code, although it needs quite a bit of cleaning up.
Also, there's a protocol limit on the number of characters/bytes in the URL, nvarchar should have enough maximum capacity, so you should need neither nvarchar(max) nor (pre-SQL Server 2005) ntext.

Categories