asp.net how to decrypt each label value in a gridview - asp.net

i have an gridview that retrieves the data via a datatable like this:
protected DataTable allClients()
{
string conn, comm, tSub, tMain;
tSub = "client_sub";
tMain = "client_main";
conn = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
comm = "SELECT * FROM [" + tSub + "] t1 LEFT JOIN [" + tMain + "] t2 ON " +
"t1.customer_ID = t2.customer_ID";
SqlConnection connection = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(comm, connection);
connection.Open();
DataTable allTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(allTable);
connection.Close();
return allTable;
}
clientGrid.DataSource = allClients();
clientGrid.DataBind();
and its working fine on retrieving the data but the problem is i am trying to decrypt the value on retrieving it.
i used this encryptor class
so how can decrypt the value of each row in the gridview.
using asp.net 4.0, thanks

Two options - you can loop around the data table in your allClients() method before returning it, or you can look into handling the row bound events when you do the data bind on the grid view - this would allow you to access each row as its created in the grid view and manipulate the data displayed.

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

Run sp_msforeachdb to select dbsize used in c#

I have a query as such:
EXEC sp_msforeachdb
'USE [?];
SELECT DB_NAME() AS [Database Name],
CAST(SUM(FILEPROPERTY(name, ''SpaceUsed''))/128.0 AS decimal(18,2)) AS [Used space(MB)]
FROM sys.database_files
Where type_desc = ''ROWS'' and
GROUP BY type_desc'
and executing this in MSSM is alright.
My problem is that I need to execute this in my application using c# and stored in a Datatable. Any idea how to do this?
Tried looking for at CommandType.StoredProcedure and CommandType.Textbut still can't figure it out.
FYI, I'm not allowed to create a new stored procedure for this.
EDIT (SAMPLE CODE)
using (SqlConnection sqlConnection = new SqlConnection(HoustonSqlCon))
{
const string query = "EXEC sp_msforeachdb 'USE [?]; SELECT DB_NAME() AS[Database Name]," +
"CAST(SUM(FILEPROPERTY(name, ''SpaceUsed'')) / 128.0 AS decimal(18, 2)) AS[Used space(MB)]" +
"FROM sys.database_files" +
"Where type_desc = ''ROWS''" +
"GROUP BY type_desc'";
using (SqlCommand comm = new SqlCommand(query, sqlConnection))
{
sqlConnection.Open();
comm.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(totalSchemas);
}
}

Select SQL Server table data using ASP.NET

I want to select/retrieve all data from SQL Server using ASP.NET.
I've tried this code...
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
The code works fine but it can select only one record from database but I want to select all the records...
Also can any one tell me that how to use two/multiple queries using only one data reader....
Any help will be appreciated...
Update: problem is when the query run then only the last record will show, but I want that all the record will show against the mentioned id...
Update 2 this is my page code, as I am new in asp.net, so how can I get the username and other data in span or p tag...
<asp:Panel ID="Panel1" runat="server" Height="140px" Width="378px">
<p>
<asp:Label ID="user_name" runat="server"></asp:Label> Commented on <asp:Label ID="date" runat="server"></asp:Label></p>
<asp:Label ID="userrcomment" runat="server" Height="31px" Width="378px"></asp:Label>
</asp:Panel>
If you are getting only one records then there are two possibilities.
"select * from comment where ID='" + st + "'" In your where condition satisfy for only one record.
You are using SqlDataReader in while loop if there are many records you got but you can only see last record bcoz it will be overwrite last record in every loop.
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
the user_name.Text will replaced with last record.
Assuming your code is otherwise working, and you want to see all the data in just the three text boxes instead of some more tabular format.
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text += drr["Username"].ToString();
date.Text += drr["Date_Created"].ToString();
userrcomment.Text += drr["Comment"].ToString();
}
Notice instead of overwriting the value of the textbox, I'm appending strings to it because I used +=. You might want to concatenate a , to it also.
More likely with multiple records though, you want to have them get in a table. The easiest and most straightforward way to do this is:
Code Behind
var cmd = new SqlCommand("select * from comment where ID=#id");
cmd.Parameters.AddWithValue("id", st);
var dt = new DataTable();
using(var con = new SqlConnection(connectionString))
{
con.Open();
dt.Load(cmd.ExecuteReader());
}
GridView1.DataSource = dt;
GridView1.DataBind();
Markup
<asp:GridView runat="server" id="GridView1" AutoGenerateColumns="true" />
You can execute multiple select queries using a single DataReader. There is an article namely,"Executing multiple SQL statements as one against SQL Server" in CodeProject. Please read it, you will get solution for sure.
using(SqlConnection conn=new SqlConnetion(ConnectionString))
{
using(SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con))
{
using(SqlDataAdapter adapter=new SqlDataAdapter(cmdd))
{
DataTable dt=new DataTable();
adapter.Fill(dt);
//Bind the datasource with a repeater control in which you can place textbox control. It will repeat for every data rows.
}
}
}
You need to place the record into a dataset for you to get all the data you're trying to Retrieve
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr = new SqlDataReader(cmdd);
DataSet ds = new DataSet();
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
user_name.Text = dr["Username"].ToString();
date.Text = dr["Date_Created"].ToString();
userrcomment.Text = dr["Comment"].ToString();
}
select/retrieve all data from SQL-Server using ASP.NET
using this SqlDataReader (sqldr) GetValue for all the records
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString);
string sql = "select * from comment where ID='" + st + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
user_name.Text = sqldr.GetValue(2).ToString();
date.Text = sqldr.GetValue(3).ToString();
userrcomment.Text = sqldr.GetValue(4).ToString();
}
sqldr.Close();
con.Close();

How to sync Datagridview and datasource when user sorts column?

I have a DataGridview in a windows form project that is directly bound to a Dataset through a SqlDataAdapter. I have one editable column which a user can edit and that works great if the user does not sort the column.
If the user sorts the column the underlying datasource gets out of sync with what the Datagridview is displaying.
What is a standard technique to keep the gridview and datasource in sync when a user sorts it?
Thanks!
As per my understanding auto sorting does not works with DataGridView, for performing sorting you need to sort the datasource and then rebind it to the GridView as shown in code below
private void Sort_DataGrid(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
// Never use Queries like this always use Stored procedures
SqlCommand myCommand = new SqlCommand("SELECT * FROM Categories", myConnection);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds, "Categories");
DataView dv = new DataView(ds.Tables["Categories"]);
if ((numberDiv % 2) == 0)
dv.Sort = e.SortExpression + " " + "ASC";
else
dv.Sort = e.SortExpression + " " + "DESC";
numberDiv++;
myDataGrid.DataSource = dv;
myDataGrid.DataBind();
}
I can't seem to find an event that triggers for clicking on the header to sort a datagridview.

Comparing cyrillic data from SQL Server table and Excel file with ASP.NET

Using ASP.NET I need to compare data loaded from Excel file with data in SQL Server table. It's data written in cyrillic.
Basically, after script creates an array list filled with data from database table, it opens Excel file, and list data from one of the column. For every data stored in Excel cell, I have to find position in mentioned array list.
I have same data in both sources, but script returns that there are no same data at all. I guess that is something related with cyrillic letters.
Part of the code used for reading Excel cells and comparing with array list looks like this:
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
Page.Trace.Write(getExcelSheetName);
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
foreach (DataRow row in dtExcelRecords.Rows)
{
Response.Write(row[0]);
Response.Write(" ");
Response.Write(MyClass.areasList.IndexOf(row[0])); // always returns -1
Response.Write(Environment.NewLine);
Response.Write("<br />");
}
Can you help me solving this please? Thank you in advance!

Resources