This c# code works fine in wpf framework.
Now I need this code in asp.net.
I am using GridView instead of DataGrid.
What changes do I have to do?
Here is my c# code:
DataRowView SelectedRowValue = (DataRowView)dataGrid1.SelectedValue;
byte[] ImageBytes = (byte[])SelectedRowValue.Row.ItemArray[1];
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO Images (Image) VALUES (#ImageSource)", con);
cmd2.Parameters.Add("#ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
cmd2.ExecuteNonQuery();
You can use Grid_RowUpdating Event using c#
protected void oGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("Label1");
TextBox txtImage = (TextBox)row.Cells[0].Controls[0];
//........
Then Update Command for MySQl which You are using//
MySqlCommand oMySqlCommand = connection.CreateCommand();
oMySqlCommand.CommandText = ""update detail set
Image='"+txtImage.Text+"'where id='"+userid+"'";
connection.Open();
command.ExecuteNonQuery();
//.......
etc//
GridView1.EditIndex = -1;
}
Related
I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.
protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
OracleConnection oConn = new OracleConnection(connStr);
oConn.Open();
string SqlText = "Select * from employees where department_id = :department_id";
OracleCommand cmd = new OracleCommand(SqlText, oConn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Varchar2;
p_department_id.Value = ddDepartments.SelectedItem.Value;
cmd.Parameters.Add(p_department_id);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dtEmployees = new DataTable();
adapter.Fill(dtEmployees);
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
dtEmployees.Dispose();
adapter.Dispose();
cmd.Dispose();
oConn.Close();
oConn.Dispose();
}
You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.
So right after:
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
Add:
Session("gvDS") = gvEmployees.DataSource;
In the page Load() method:
if (Session["gvDS"] != null && IsPostBack)
{
gvEmployees.DataSource = Session["gvDS"];
gvEmployees.DataBind();
}
else
BindGridView(); // you initial gvEmployees binding method
Please see my answer #:
Asp.net Web Forms GridView Dynamic Column Issue
How would I be able to grab the value from a dropdown list control after the control has been bound with a filled data set? Specifically, this control lives in my footer template and when the user tries to add a new row the selected item needs to be retrieved. The problem is after the dropdown list has been populated when you click on "add new" the value always returns null.
ROW COMMAND FUNCTION:
protected void userView_RowCommand(object sender, GridViewCommandEventArgs e)
{
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole");
string sqlCommandText = "INSERT INTO Users(USERNAME, PHONE, EMAIL, ROLEIDFK, DEPTIDFK, ACTIVE) VALUES(#username, #phone, #email, #roleidfk, #deptidfk, #active)";
scmd.Parameters.AddWithValue("#roleidfk", addUserRole.SelectedValue.ToString()); // >>>> Returns "AddUserRole was null"
}
DROPDOWN DATABINDING:
private DataTable GetData (string query)
{
var connection = sqlConnect.connect();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connection.ConnectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
protected void userView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
if ( e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
//query.addDataSetDdl(roles, "DESCRIPTION", "ROLEID", ddlUser);
ddlUser.DataSource = GetData("SELECT * FROM Roles");
ddlUser.DataTextField = "DESCRIPTION";
ddlUser.DataValueField = "ROLEID";
ddlUser.DataBind();
}
The problem is that the FindControl call does not use the correct id of the dropdpwnlist - at least it differs from the one that you use when databinding the dropdownlist:
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole")
vs
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
FindControl returns null if the control cannot be found, so if you use the correct id, the problem should be solved.
I need to update my whole gridview details via single button click. Now I have a coding. But I edit the grid view and click the update button, then the first row only update, remainins are not update. pls help. This is my code.
protected void Button8_Click(object sender, EventArgs e)
{
int RowIndex = 0;
{
GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
DataBind();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Because you are only specifying the index of first row. You need to loop through each row like this:-
int totalRows = GridView1.Rows.Count;
for (int RowIndex = 0; i < totalRows; RowIndex++)
{
GridViewRow row = GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
}
Response.Redirect(Request.Url.AbsoluteUri);
Also, I would suggest to create a separate layer to handle DB operations. Consider using the using statement while executing SQL related queries. Also read Can we stop using AddWithValue.
Update:
Side Note:
1) Bind your gridview inside !IsPostBack.
2) Don't bind the gridview again, either inside the loop or outside.
3) I don't find any reason to update the EditIndex using GridView1.EditIndex. Don't update it.
using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}
I had gridview which on databound I need to hid Image control so I did this code but error apear( grid view dosenot containe defination of RowIndex) when i tried to find control
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Img = GridView1.Rows[e.RowIndex].FindControl("Logo") as Image ;
using (SqlConnection con = Connection.GetConnection())
{
string Sql = "Select Logo From Model where Id=#Id";
SqlCommand com = new SqlCommand(Sql, con);
com.Parameters.Add(Parameter.NewInt("#Id", DDLModel.SelectedValue));
com.CommandType = CommandType.Text;
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
string Img2 = dr["Logo"].ToString();
if (Img2 == System.DBNull.Value.ToString())
{
Img.Visible = false;
}
}
}
}
GridViewRowEventArgs contains the row so you could try:
image = e.Row.FindControl("Logo") as Image;