Sameer Shaikh
Sameer Shaikh

Reputation: 67

how to set column as readonly in gridview

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();
        }

Upvotes: 2

Views: 17688

Answers (4)

RUSHABH SHAH
RUSHABH SHAH

Reputation: 91

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'

Upvotes: 0

Jordan Andrews
Jordan Andrews

Reputation: 163

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

Upvotes: 2

Kishor Khatri
Kishor Khatri

Reputation: 31

RowDataBound event of gridView1

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

Upvotes: 3

Lajja Thaker
Lajja Thaker

Reputation: 2041

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.

Upvotes: -1

Related Questions