passing a datalist value using session in asp.net - c#

I'm actually storing a value using session and then redirecting to other page using image button where based on the session value I'm fetching the Data from database. I'm getting an user defined exception in the line.
please help!
adap.Fill(dt1);//[SqlException (0x80131904): Incorrect syntax near '='.]
And this my coding.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender as ImageButton;
string modelId = btn.CommandArgument;
Session["modelid"] = modelId;
Response.Redirect("details.aspx");
}
public partial class details : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=" + Session["modelid"], con);
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}

Cast the session object to a string first.
(String) Session["modelid"]

I recommend you to avoid using string concatenation for command creation - use parameters instead.
Also, you have to check whether Session["modelid"] has value or not, because parameter with null value will cause exactly the given message:
The parameterized query '(#id nvarchar(4000))select * from details1
where Modelid=#id' expects the parameter '#id', which was not supplied
So, the code will be:
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
var id = Session["modelid"];
if (id != null)
{
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=#id" , con);
adap.SelectCommand.Parameters.AddWithValue("#id", );
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}
}
Or use the Page.IsPostBack property if it is guaranteed that Session["modelid"] will be set after the first postback.
Or just use some default value for it.
P.S.: Also, it is not a good idea to use instance level connection where you can't Dispose (Close) it in a deterministic way. It is better to make it method level variable and use it with using clause:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True"))
{
// ...
}
}

Related

Updating/saving data to an SQL database table using c# winforms

I'll start off by saying that I'm pretty inept at coding (have yet to learn how to utilize classes and how they work in depth), and that I've never worked with sql before doing this project.
The idea here is that you connect to an sql database, after which a datagridview element gets filled with data from a table called TABLE_1 by default. The user should then be able to input, delete and save data.
The first two work operations work perfectly, but the saving is the problem. I've banged my head against a wall for about 4 days trying to get the saving to work, but I just cant get it to do so. The saving is done with the method Button3_click.
Any insight as to what I should do?
Is the main chunk of the code where you connect the part where I'm
messing up?
//initialize the classes I guess, on some youtube guides they did so
SqlConnection con;
DataSet ds;
SqlDataAdapter a;
DataTable t;
SqlCommandBuilder scb;
static string tablename = "TABLE_1";
string constring;
//connect button
private void button1_Click(object sender, EventArgs e)
{
try
{
//connect using info from textboxes, connection is ok
constring = "server=" + Server.Text + ";database=" + DB.Text + ";UID=" + UID.Text + ";password=" + Password.Text;
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
Save.Enabled = true;
//check if table name is empty, if so default to TABLE_1
if (textBox1.Text != "")
{
tablename = textBox1.Text;
}
else
{
tablename = "TABLE_1";
}
a = new SqlDataAdapter("SELECT * FROM " + tablename, con);
DataTable t = new DataTable();
a.Fill(t);
datagrid.DataSource = t;
//
label5.Text = Server.Text;
con.Close();
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
//save button
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
DataTable t = new DataTable();
a.TableMappings.Add(tablename, "t");
scb = new SqlCommandBuilder(a);
a.Update(t);
con.Close();
}
Use the following example which sets up the adapter, dataset and table name as private variables.
Also, I recommend to never use one letter variable names as a) it's difficult to debug b) when getting into more lines of code it's going to be difficult to know what a variable is for.
Next up, using SELECT *, it' unknown if you have setup a auto-incrementing primary key which is needed to perform updates. In the example below, Id is auto-incrementing.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsDataAdapterExample
{
public partial class Form1 : Form
{
private SqlDataAdapter _companiesSqlDataAdapter;
private DataSet _companiesDataSet;
private string _tableName = "Companies";
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
_companiesDataSet = new DataSet();
_companiesSqlDataAdapter = new SqlDataAdapter(
"SELECT Id, FirstName, LastName, PhoneNumber, City FROM dbo.Companies;",
"Data Source=.\\sqlexpress;Initial Catalog=ForumExample;" +
"Integrated Security=True");
var builder = new SqlCommandBuilder(_companiesSqlDataAdapter);
_companiesSqlDataAdapter.Fill(_companiesDataSet, _tableName);
dataGridView1.DataSource = _companiesDataSet.Tables[_tableName];
}
private void SaveButton_Click(object sender, EventArgs e)
{
_companiesSqlDataAdapter.Update(_companiesDataSet, _tableName);
}
}
}

Using SAME Textbox to search and insert data in dataGridView

I have a Textbox with which I want to be able to Search and Insert data into Table. Insert works fine with one exception: When I try to Insert data that isn't already in DB(it's searching while I'm typing) it gives me:
"Exception User-Unhandled System.NullReferenceException: 'Object
reference not set to an instance of an object.'
System.Windows.Forms.DataGridView.CurrentRow.get returned null.
I think I'm missing something in the Search code.
//UPDATE: All of the code.// This is my Insert and Search code:
namespace UDDKT
{
public partial class FrmGlavna : Form
{
DataSet ds = new DataSet();
SqlDataAdapter DaDavaoci = new SqlDataAdapter();
SqlDataAdapter DaAkcije = new SqlDataAdapter();
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
public FrmGlavna()
{
InitializeComponent();
}
//Popunjava DataGridViews sa podacima iz baze
private void FrmGlavna_Load(object sender, EventArgs e)
{
SqlCommand SlctDavaoci = new SqlCommand("SELECT * FROM Davaoci ORDER BY DavaocID DESC", cs);
DaDavaoci.SelectCommand = SlctDavaoci;
DaDavaoci.Fill(ds, "TblDavaoci");
SqlCommand SlctAkcije = new SqlCommand("SELECT * FROM AkcijaDDK", cs);
DaAkcije.SelectCommand = SlctAkcije;
DaAkcije.Fill(ds, "TblAkcije");
DgDavaoci.DataSource = ds.Tables["TblDavaoci"];
}
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
//Osvježava DataGridView nakon unosa/izmjene/brisanja podataka u bazu
private void RefreshTable()
{
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
String query = "SELECT * FROM Davaoci ORDER BY DavaocID DESC";
SqlCommand cmd = new SqlCommand(query, cs);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DgDavaoci.DataSource = dt;
}
//Čisti TextBox nakon upisa/izmjene/brisanja podataka u bazu
public void ClearTxtBx()
{
TxtIme.Clear();
TxtPrezime.Clear();
TxtTezina.Clear();
TxtAdresa.Clear();
TxtBrojTel.Clear();
TxtBrojLK.Clear();
}
//Upis podataka u Tabelu Davaoci
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(query, cs))
{
command.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
command.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
command.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
command.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = TxtDatumRodjenja.Text;
command.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
command.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
command.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
command.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
command.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
command.ExecuteNonQuery();
cs.Close();
RefreshTable();
ClearTxtBx();
}
}
//Pretraga postojećih Davalaca
private void TxtIme_TextChanged(object sender, EventArgs e)
{
(DgDavaoci.DataSource as DataTable).DefaultView.RowFilter = string.Format("Ime LIKE '{0}%'", TxtIme.Text);
}
}
}
}
Here is the MockUp of the Form before I begin to type/search/insert Data that isn't already in the Table (First Textbox*).
And after I start typing Name(Име) that starts with an "A" (name that isn't already in the Table).
I want to Search DB for that Column, but if there aren't any existing names, I want to be able to continue typing (without interuption) so that I can Insert new data into table.
DgDavaoci.CurrentRow in your DgDavaoci_SelectionChanged method is null, so attempting to access DgDavaoci.CurrentRow.Cells["DavaocID"] throws the NullReferenceException. The reason, best I can tell, is as follows:
You begin to type a value into your text box, a value that happens not to be found in the data set. As you type, you cause the TxtIme_TextChanged method to execute. It filters according to your search, and since the value is not found, it filters out every row in the set. Here's the important part: whenever the data set is filtered, it has the possibility of causing DgDavaoci_SelectionChanged to execute. Since the selection changed from the first row to no row at all (since there are no filtered rows to display), this method does execute. Now, when the method attempts to access the current row, there is no current row, and so we get a null here. Attempting to access a field of null throws the exception you're getting.
How can you fix this behavior? A simple null-check in DgDavaoci_SelectionChanged should do the trick. It looks to me like you can simply return from that method if(DgDavaoci.CurrentRow == null), or you can code in additional behavior. Just perform a check so that you don't reference the null object.
Probably the filter inside TxtIme_TextChanged is causing the DataGridView's SelectionChanged event to fire and the code is entering DgDavaoci_SelectionChanged. The exception indicates that DgDavaoci.CurrentRow is null, so you'll need to handle the case where DgDavaoci.CurrentRow is null in DgDavaoci_SelectionChanged.
A simple way to deal with this would be to just check DgDavaoci.CurrentRow is null and return from the function if that evaluates to true.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
It looks like you might have a second DataGridView (DgAkcije) that is designed to show the details of the currently selected row in DgDavaoci. So, another approach might be to just clear DgAkcije if DgDavaoci.CurrentRow is null.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
DgAkcije.DataSource = null; //I'm not 100% sure this will work, I haven't tested it.
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
Ultimately, however, you'll have to decide what you want to happen when DgDavaoci_SelectionChanged is called but DgDavaoci.CurrentRow is null.
Solution if anyone else is interested:
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow != null)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
}

search an item by name and display the content in another page

I want to display an item information in gridview from data base by using it name , and i want the gridview to be in another page
i tried this code,,but it didn't work
in the first page
protected void Page_Load(object sender, EventArgs e)
{
}
public string txt
{
get
{
// Return the actual name if it is not null.
return TextBox1.Text ?? string.Empty;
}
}
}
in the second page
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=FATIMAH;Initial Catalog=makeup;Integrated Security=True");
string find = "select * from product where(name like '%' +#name+ '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#name", SqlDbType.NChar).Value = txt;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
You can pass parameter to another page using QueryString. onclick event of button on First page do this:-
protected void Button1_Click(object sender, EventArgs e)
{
string search_word = TextBox1.Text.ToString();
Response.Redirect("~/secondpage.aspx?srch_word=" + search_word);
}
and on second page request the querystring:-
protected void Page_Load(object sender, EventArgs e)
{
string search = Request.QueryString["srch_word"];
//execute sql query to perform search operation
}
Your query looks off to me. Try "select * from product where name like '%#name%'"
Also for your parameters you can just cmd.Parameters.AddWithValue("name", nameVariable);
Not sure why you would need to specify the type in this situation.
your problem is not the SQL query, your problem is passing parameter to another page.
for this reason you can do it in at least 4 different ways.
Send Text by query string
Pass it via Post Data
Pass it via Cookie
Send it via Session
in this case you can use query string, but you have to care about security issue.
BTW, it depends on how you redirect to 2th page.

how can i search a string in sql database table

this is my program
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
if (value.Contains(SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword=#value"))// <--MY PROBLEM
{
con.Open();
lblStatus.Text = "Normal"; <-- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
Frdsclass.Text = "Just Friend"; <--- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}
how can i search a word or sentence in database table?? is my method correct?? plz help if u have a solution
your question is not quite clear. If you want to search a substring in a varchar field you can do it with a like
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%yoursearchstring%'
if you wanto look in different fields you can chain with ...or yourotherFild like '%yousearchstring%'
if you want to search those records that start with your searchstring the condition is
..like 'yoursearchstring%'
public string GetValue (string searchValue)
{
using(SqlConnection connection = new SqlConnection(connString));
using(SqlCommand cmd = new SqlCommand(
"select keyword from messageanalysis where value=#value")
{
cmd.AddParameter("#value",searchValue);
var result = cmd.ExecuteScalar();
return (result == null)? null : result.ToString();
}
}
....
var keyword = GetValue(value);
if (keyword != null && value.Contains(keyword)){
....
You could do something like this. I've separated your select statement into a different function. This will look for your value that you pass in and return your keyword. if it doesn't find it, the function returns null. I then set it to check and see if the keyword is null (since null is not found) and if it finds the value to execute the conditional code.
Try this...
NOTE:ExecuteScalar() will returns the first record of the resultset.
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword = #value")
cmd.Parameters.AddWithValue("#value", Keywordtextbox.text);
cmd.Connection=con;
con.Open();
if (Keywordtextbox.text.Contains(cmd.ExecuteScalar()))
{
lblStatus.Text = "Normal";
Frdsclass.Text = "Just Friend";
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}
if your textfield can contain more than one word you have to separate the words in the appropriate number of strings and then
select the records with a like saerch as shown in my previous answer
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%string1%' or yourvarcharfield LIKE '%string2%' or ...
as the textfield can have various numbers of words you have to build your sqlcommand with a stringbuilder.

Datagrid refresh not working

I have a datagrid to display some information from a SQL table, and then a simple textbox and button to allow users to add records to the database. Problem is, when the user clicks Add, the datagrid SHOULD update, but it doesn't, any ideas? The code in question is as follows:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = Session["username"].ToString();
datetime.Text = DateTime.Now.ToString();
BindData();
}
protected void BindData()
{
string SQLQuery = "SELECT * From Filters";
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
DataSet resultsDataSet = new DataSet();
MyConn.Open();
OleDbDataAdapter DataAdapter = new OleDbDataAdapter(SQLQuery, MyConn);
DataAdapter.Fill(resultsDataSet);
DGFilters.DataSource = resultsDataSet;
DGFilters.DataBind();
if (resultsDataSet.Tables[0].Rows.Count == 0)
{
no_records.Visible = true;
DGFilters.Visible = false;
}
else
{
DGFilters.Visible = true;
no_records.Visible = false;
}
MyConn.Close();
}
protected void AddFilter_Click(object sender, EventArgs e)
{
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
MyConn.Open();
string SQLInsert = "INSERT INTO Filters (FilterString) VALUES ( '" + FilterToAdd.Text + "')";
OleDbCommand MyCmd = new OleDbCommand(SQLInsert, MyConn);
MyCmd.ExecuteNonQuery();
MyConn.Close();
DataBind();
}
Any ideas?
At the bottom of your AddFilter_Click method you need to call your own BindData() so the grid can be refreshed with the new record. Right now you're calling DataBind(), which is a method on the base class Control, which is being applied to your entire web form. I'm guessing this isn't doing much of anything.
Also, in your Page_Load method, you can probably change this:
BindData();
to
if (!Page.IsPostBack)
BindData();
so that you don't bind your grid twice when the user clicks on the 'add' button.

Categories

Resources