how to set column as readonly in gridview - asp.net

I am using a gridview Edit to edit the values i have in my gridview, when i press edit, all columns can be edited, i would like that one of the columns is not allowed to be edited.
Is there any way i can do this?
This is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
onrowdeleting="GridView1_RowDeleting" AutoGenerateEditButton="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" >
</asp:GridView>
This is my aspx.cs code:
public void loadCustomer()
{
SqlConnection objConnection = new SqlConnection("Data Source=localhost;Initial Catalog=SampleApplication;Integrated Security=True");
objConnection.Open();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandText = "Select * from Customer";
objCommand.Connection = objConnection;
objCommand.ExecuteNonQuery();
DataSet objds = new DataSet();
SqlDataAdapter objadap = new SqlDataAdapter(objCommand);
objadap.Fill(objds);
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
objConnection.Close();
}

RowDataBound event of gridView1
((BoundField)gridView1.Columns[columnIndex]).ReadOnly = true;

I know this is really old but I need to put the answer here for others who shared my issue. Regardless, I've been struggling with this non-stop for a couple of days now. Everyone seems to be posting code for VB, when your problem is clearly posted in C#.
What you're looking for is:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columntobedisabled].Enabled = false;
}
where 'columntobedisabled' is index number of the column to be disabled...eg. 1

In case of C# Website or WebForm enter the following code in Page_Load() in code behind file
protected void Page_Load(object sender, EventArgs e)
{
// Your code
((BoundField)GridView1.Columns[columnIndex]).ReadOnly = true;
}
Doing this will also help in overcoming the error
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index'

You need to give rights "ReadOnly= true" to that column which you not like to be edit.
e.g .
GridView1.columns[1].ReadOnly= true;
You can use this line in RowDataBound event of GridView.

Related

Gridview selected value always returns 0?

I am trying to delete a row from a gridview if "Web drop course" option is selected. Here is the UI:
And the code:
for (int i = 0; i < showCourses.Rows.Count; i++)
{
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
dropList.Add(showCourses.Rows[i].Cells[2].Text +showCourses.Rows[i].Cells[3].Text );
}
}
Here is the dropdown list:
<asp:ListItem Selected="True" Value="0">No Action</asp:ListItem>
<asp:ListItem Value="1">Web Drop Course</asp:ListItem>
The problem is, ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue always returns 0 whether I choose No action or Web drop course. Can anyone see the problem?
Thanks
You are most likely not protecting against rebinding your data on postback. When your event that causes postback fires, the page load event fires before this. If you are binding in page load without a check for postback, you are basically resetting your data and then going into your event handler.
The page life cycle might be a good read: Page Life Cycle
Considering your previous post, you are rebinding the gridview on each postback. Wrap those lines with a !IsPostback conditional. Better wrap those into a method (say PopulateGrid()) and call it. Then, you can re-call that method in other situations where you might need to rebind the data (OnPageIndexChanged for example). Change your Page_Load method like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "select * from RegisterTable where StudentID='" + MyGlobals.currentID + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
showCourses.DataSource = tab;
showCourses.DataBind();
}
}

Table Format From Excel To Gridview ? In Asp.Net?

In web application [asp.net], i am trying to get the excel data in gridview. It is working fine, but the format of the table in gridview is different from the excel. I mean format of the table is different from excel to gridivew. I am placing the screen shot please find them First is Excel Format :
second one is Gridview Screent shot which is in .aspx page.
Please help me for formating the table design. Thank you.
Try from this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=138In one video of learning Linq I saw this tag but not remember this perfectly. But I test this, also you can make table with your linq code.Have good time!
Try this code to import excel to Gridview:
using System.Data;
public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check file is available in File upload Control
if (FileUpload1.HasFile)
{
//Store file name in the string variable
string filename = FileUpload1.FileName;
//Save file upload file in to server path for temporary
FileUpload1.SaveAs(Server.MapPath(filename));
//Export excel data into Gridview using below method
ExportToGrid(Server.MapPath(filename));
}
}
void ExportToGrid(String path)
{
OleDbConnection MyConnection = null;
DataSet DtSet = null;
OleDbDataAdapter MyCommand = null;
//Connection for MS Excel 2003 .xls format
MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");
//Connection for .xslx 2007 format
// MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + "';Extended Properties=Excel 12.0;");
//Select your Excel file
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DtSet = new System.Data.DataSet();
//Bind all excel data in to data set
MyCommand.Fill(DtSet, "[Sheet1$]");
dt = DtSet.Tables[0];
MyConnection.Close();
//Check datatable have records
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
//Delete temporary Excel file from the Server path
if(System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
}
One of the main visible problem is your Excel spreadsheet has sub tables (for example, Cargo Qty). In 'pure' html, this can be done using COLSPAN or ROWSPAN, but with the GridView, it's not that easy, unless you create sub gridviews, like this:
<asp:GridView runat="server" ...>
<Columns>
<asp:BoundField HeaderText="MyHeader" DataField="MyField1"... />
...
<asp:TemplateField HeaderText="MySubGridHeader">
<asp:GridView runat="server" ...> // need to databind this
<Columns>
<asp:BoundField HeaderText="MySubHeader1" DataField="MyField2"... />
<asp:BoundField HeaderText="MySubHeader2" DataField="MyField3"... />
</Columns>
</asp:GridView>
</asp:TemplateField>
</Columns>
</asp:GridView>
Otherwise I suggest you go for commercial packages which can display advanced grids, such as this one for example: SPREAD (note: I'm not affiliated and I have not tested it).

Insert data into Access database upon checkbox-click event of ASP.net

I'm trying to make asp.net page
Criteria
I have product list. (using listview)
ProductID Proudct name Price ADD TO CART(checkbox)
Now I am using access 2007 for database. C# for code behind file. I want add product in to database which is on the event of checkbox. So if user check 10 item check box Out of 20 . I want write insert query on event of checkbox
Is it possible to do it? If it possible please provide me knowledge/ code how can I do it?
Please keep in mid that I am new and learning stage so make it easy or put gudieline in comments.
It sounds like you want to use the OnCheckedChanged event.
<asp:CheckBox ID="CheckBox1" runat="server" Text="Hello World!" OnCheckedChanged="CheckBox1_CheckedChanged" />
And in your code behind:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
//CREATE CONNETION HERE
OleDbConnection conn = new OleDbConnection ("<YOUR CONNECTION STRING HERE>");
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
//CREATE YOUR OWN INSERT/UPDATE COMMAND HERE
command.CommandText= "<YOUR COMMAND TEXT HERE>";
command.Parameters.Add ("#Argument1", OleDbType.String).Value = CheckBox1.Text;
command.ExecuteNonQuery();
conn.Close();
}

datagridview in asp.net retrieve value

i am working on visual stdio 2008 and my database is in sql server 2005
MY table has three columns
1. SenderName
2. RecieverName
3. Message
i have displayed this table in GridView and add a button named as Reply
so my grid view look's some what like this
SenderName|RecieverName| MessAge|REPLY BUTTON
now this what i want to do
when Button is Clicked in My gridView i need to get data of that specific row
i.e Sender's NAme so that i can Reply him/her ?
can any one help????
Here's a sample:
Markup:
<asp:GridView
runat="server"
ID="gvEmails"
OnSelectedIndexChanged="gvEmails_SelectedIndexChanged">
<Columns>
<asp:ButtonField CommandName="Select" ButtonType="Button" Text="Send" />
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("SenderName");
dt.Columns.Add("ReceiverName");
dt.Columns.Add("Message");
DataRow dr;
dr = dt.NewRow();
dr["SenderName"] = "John Doe";
dr["ReceiverName"] = "Jane Doe";
dr["Message"] = "Hi, Jane.";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["SenderName"] = "Michelle Smith";
dr["ReceiverName"] = "Mike Smith";
dr["Message"] = "Yo, Mike.";
dt.Rows.Add(dr);
gvEmails.DataSource = dt;
gvEmails.DataBind();
}
protected void gvEmails_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvEmails.SelectedRow;
Response.Write("Send email to " + row.Cells[1].Text);
}
there is a selected index changed function in the properties.
Captuer the selected index and get the cell value of that selected index.
Then continue whtever u want.
There are many different ways of doing this. The easiest, if you only need a single value, would be to bind the value to the CommandArgument of your Reply button. Then add an OnClick handler to your button. Then in the OnClick method you can get the name from the CommandArgument.
If you need more than a single value from the row, you will need to do a little more work. You can setup an event handler on the GridView to capture the event of the index changing. This will provide some event arguments that has a NewSelectedIndex. That will tell you what row was selected. Depending on how your data is bound to your GridView, you can access the data again to get the values you need, or you can set the columns to be a DataKey in the GridView and access them that way.

Getting Row's Name in a DataList

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.
<HeaderTemplate>
'Get data row names
'Maybe something like Container.DataItem(row)?
</HeaderTemplate>
If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.
<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
ShowHeader="true" >
<HeaderTemplate>
</HeaderTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach (DataColumn col in dt.Columns)
{
Literal lit = new Literal();
lit.Text = col.ColumnName;
e.Item.Controls.Add(lit);
}
}
}
You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.
((DataRowView)Container.DataItem).DataView.Table.Columns
If this works, you can loop through this collection and inspect each item's ColumnName property.
A better idea would be to either:
Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.

Resources