I am currently working on my first website. The problem I have encountered is the following: I have created a paged titled "CustomerList" that obviously list customers from an sql server DB. I have made the records clickable without using the select button that is included in the GridView. When I click a record, it takes me to my desired page. However, I can't seem to find a way to write an sql query from that click event to my desired page. The following is my code for the click event:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
if (row.RowIndex == 0)
{
Response.Redirect("UsageHistoryPage.aspx? EntityID="
+ row.Cells[0].Text);
}
}
As you can see, when I click an index, I go to the "UsageHistoryPage". I've also added row.cells.[0] to take that data and write it to the UsageHistoryPage, which in my case, would be the customers name at the top of the page. Can someone please help me with this? Does anyone have a good tutorial link? thanks.
You can try with this code - Add this code on your UsageHistoryPage
var input = Response.QueryString["EntityId"];
var connectionString = "...";
var queryString = "SELECT Name FROM TABLE WHERE COLUMN=#EntityId";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
using(var command = new SqlCommand(queryString, connection))
{
Command.Parameters.AddWithValue("#EntityId",input)
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Response.Write(String.Format("For Rick Your Name is here{0}", reader[0]));
}
}
}
#Rick you may want to look at how to check if a row is selected for example you don't need the for loop but in my case example need to check if RowIndex is = 1 or > 0 not ==0
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
What you need to do is something like this to make sure that a Row has been selected
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewRow row = GridView1.SelectedRow;
if (this.row.SelectedRows.Count == 1)
{
Response.Redirect("UsageHistoryPage.aspx?EntityID=" + row.SelectedRows[0].Cells[0].ToString());
}
}
If you want to have the Customer's name show up, on the Page Load of the UsageHistorPage.aspx add this code
String strCustName = Request.QueryString["EntityID1"];
this.Page.Title = strCustName;
try something like that.. please let someone here know if any of the ideas are working for you.
Related
Goal:
My goal is to format 1 column to password characters *.
Resources I have tried:
I have used an example from here :
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.cellformatting?view=netframework-4.8
and tried this answer here:
https://stackoverflow.com/a/38074239/12485722
This is my current code to load DataGrid View:
private void Form3_Load(object sender, EventArgs e)
{
RefreshGrid();
}
//Refresh Data Grid from external Forms
public void RefreshGrid()
{
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString()))
{
using (var mySqlDataAdapter = new MySqlDataAdapter("select * from user", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
}
}
}
This simply loads up the DataGridView with Usernames and passwords.
Now I need to format 2nd column to password characters, so the passwords do not show as text but formatted as *.
I have tried adding this piece of code from the 2nd resource mentioned above:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 && e.Value != null)
{
e.Value = new String('*', e.Value.ToString().Length);
}
}
This does not work - no errors show up, but I have noticed this references is set to 0.
(Note: this is what it should be)
Question:
I am confused where it is going wrong.. can somebody assist me to achieve this task?
Update (1) - Events and cell formatting not showing:
Your method is not wired to an event of GridView (thats why it has 0 references, because nothing is using your function).
The solution in the mentioned link is correct, but you should wire your method to an event in designer (right click on grid view > properties > events) and choose an event to fire up in CellFormatting event. Also dont forget to handle EditingControlShowing, but everything what you need is already written in a solution thread that you mentioned.
Why don't you modify your query to just say the below:
select username, repeat('*', length(password)) from users
I have doing billing application with Windows Forms. I have there datagridview:
Datagridview with colums
And when I type number to first column (Tuotekoodi / product code in english), for example in picture I have typed number 1 to first column, and then it automatically fill "Nimike" and "á Hinta" columns from database.
So my problem is that I can't edit "Nimike" or "á Hinta" columns anymore. I can but when I move to next column it reads same values back to columns. So how I can edit values in "Nimike" and "á Hinta" columns after it reads values from database to those columns?
And here is my codes where have cellValueChanged event:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
DataGridViewTextBoxCell cb = (DataGridViewTextBoxCell)dataGridView1.Rows[e.RowIndex].Cells[0];
if (cb.Value != null)
{
con = new SqlConnection(connectionString);
con.Open();
SqlCommand command = new SqlCommand("SELECT name, price FROM product where productID=#pid", con);
command.Parameters.AddWithValue("pid", cb.Value.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
dataGridView1.CurrentRow.Cells["productName"].Value = reader["name"];
dataGridView1.CurrentRow.Cells["productPrice"].Value = reader["price"];
}
}
con.Close();
}
}
And CurrentCellDirtyStateChanged event which makes changes to columns immediately when typed to first column.
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Cheers
Teme
You need to unsubscribe the function from the event after the code done for the first time to make the code runs only once. This will be like Form1.DatagridView.CellValueChanged -= dataGridView1_CellValueChanged;
I posted this not long ago, but no I have to update the question to ensure I get the right answer.
I have a GridView. I need to update an SQL table based on values from the GridView.
When a user clicks the default EDIT button on the GridView, changes whatever they change, then hits UPDATE. Here is where I run into problems. I've tried multiple OnRowEditing, OnRowUpdating, OnRowUpdate as the button control.
Here is the code I use to that.
protected void gvReviewedPolicy_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DateTime dateTime = DateTime.Now;
//GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
//string Emailed = editRow.Cells[7].Text;
//string UniqClient = editRow.Cells[1].Text;
//string UniqPolicy = editRow.Cells[3].Text;
string UniqClient = gvReviewedPolicy.SelectedRow.Cells[2].Text;
string UniqPolicy = gvReviewedPolicy.SelectedRow.Cells[3].Text;
//string Email = Emailed.ToString();
//string dt = dateTime.ToString();
//string Up = UniqClient.ToString();
MessageBox.Show(UniqClient);
MessageBox.Show(UniqPolicy);
//MessageBox.Show(dt);
string query = "UPDATE [Reviewed_Renewal_Policy] SET [DateUpdated] = #dateTime where ([UniqClient] = #UniqClient) AND ([UniqPolicy] = #UniqPolicy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=TestDB;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqClient", UniqClient);
comm.Parameters.AddWithValue("#UniqPolicy", UniqPolicy);
//comm.Parameters.AddWithValue("#Emailed", Emailed);
comm.Parameters.AddWithValue("#dateTime", dateTime);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
}
I have some commented out because I was trying different things. However, the code that says
GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
string Emailed = editRow.Cells[7].Text;
string UniqClient = editRow.Cells[1].Text;
string UniqPolicy = editRow.Cells[3].Text;
It's supposed to access the values in those cells when UPDATE button is pushed. However, using MessageBox.Show , comes back blank.
Anyone have any idea how I can capture those values after hitting Edit, then the default UPDATE button?
I've tried to make that Winforms Datagrid usable for "write through" in the past, by implementing an DataGridView subclass (this allows you to access everything) but since immutable databases and queue transactions came into view, my Access-flavour DataGrid did not survive modern paradigm. Nowadays I tend to support ASP.NET MVC 5 to "edit" databases.
Anyway have you considered to connect a DataSource ? You don't have to access cells.. you can update using a connection like
private SqlDataAdapter daGrid = new SqlDataAdapter();
and this type of approach, you will have to fill in the details yourself, the complete code consists of several classes and is too large to post,
protected void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
/// .. perform actions according to keyboard events ..
/// .. for example below one ..
}
public override void UpdateAfterEditGrid(DataSet ds, DataGridView dataGridView1, bool DoRestoreCursor)
{
if (daGrid != null)
{
if (conn.State == ConnectionState.Closed) conn.Open();
dataGridView1.EndEdit();
try
{
if (ds == null)
{
//DataGridView dgv = dataGridView1;
//Console.WriteLine("Go datasource update .. " + dgv[cColumnIndex, cRowIndex].Value);
daGrid.Update((DataTable)dataGridView1.DataSource);
}
else daGrid.Update(ds);
LoadGridRestoreCursor(dataGridView1, DoRestoreCursor);
}
catch { ErrorReporting.ErrorMessage("== cannot update this content =="); }
}
}
On the first column is the id and want to select it to be redirected to a page that has more details that row.
He goes good if datasource is not changed but if it is modified or receive ID of the initial data, or gives me error for that initially did not have many rows.
My code is:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.DataBind();
GridViewRow row = GridView1.SelectedRow;
string strCell = row.Cells[1].Text;
string myPageUrl = "Meci.aspx?ID=" + strCell;
Response.Redirect(myPageUrl);
}
Please tell me how can I change it to work well!
I have a GridView control that reads from a stored procedure in a SQL Server 2008 database and I am trying to change the backgound color of a row is a certain cell contains certain text. For whatever reason, the solution that I've come up with only works if there is more than one row in the GridView. If there is only one row in the GridView, then the row color of that row isn't changed. I'll post more code if needed, but I'm using the OnRowDataBound
event of the GridView control.
c# for the OnRowDataBound event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//in every row I would like to check the text of the second cell
if (GridView1.Rows[i].Cells[1].Text == "C6N")
{
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
Here is the structure of the GridView control
columnName1 column1Desc columnName2 column2Desc
one C6N two zzz
The intent is to change the row color of the GridView if column1Desc is equal to C6N
Below is the button click that binds the GridView. Underneath if(rdr.HasRows) I wrote to the response object and it is in fact printing the correct value of C6N, but when the result set is only one row, the formatting change doesn't take place.
protected void Button2_Click(object sender, EventArgs e)
{
//craete the drugString variable
string drugString = string.Join(string.Empty,druglist.ToArray()).TrimEnd(',');
//create the connection string
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
//create the connection object
using (SqlConnection con = new SqlConnection(cs))
{
//create the command object
using (SqlCommand cmd = new SqlCommand("spMakeTempTable2", con))
{
//don't forget to open the connection
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#drugList", drugString);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
if (rdr.HasRows)
Response.Write(GridView1.Rows[0].Cells[1].Text);
//this line prints to the screen as it should
else
Response.Write("There were no drug combinations present");
}
}
First thing - you don't need to loop through your gridview rows because this method gets called with EVERY row anyway.
You already know the row you want to query as it just called this method and passed information via the GridViewRowEventArgs property.
So something like this may suit better:
GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
// you only want to check DataRow type, and not headers, footers etc.
if (e.Row.RowType == DataControlRowType.DataRow) {
// you already know you're looking at this row, so check your cell text
if (e.Row.Cells(1).Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
Also - are you using a template to house the text you're checking? Because if you are, you need to get the control that the text is in - rather than just Cell(1).Text - as this will return all manner of things OTHER than your text.
E.G if you have the text in a label, then check the text of the label instead, by using this instead
Label lbl = (Label)e.Row.FindControl("myTextLabel");
if (lbl.Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}